An assignment operator functions to change the value that is stored inside a variable. In order for the operator to change a value, the variable must be declared beforehand. Also remember that we can declare a variable and assign it a value at the same time. Look at the code below for an example of the three assignment operators we will discuss: '=', "+=", and "-=".
package exlcode;
public class AssignmentStatementExample {
public static int exampleVariableOne = 10;
public static int exampleVariableTwo = 50;
public static void main(String[] args) {
exampleVariableOne = exampleVariableOne + exampleVariableTwo;
exampleVariableTwo += 5;
exampleVariableTwo -= 2;
System.out.println(exampleVariableOne);
System.out.println(exampleVariableTwo);
}
}
Something to keep in mind when assigning values is that the calculation on the right side of the equal sign is completed before assigning the variable on the left with its new value. As we see in the code above, exampleVariableOne
and exampleVariableTwo
are added before being assigned to the new value of variable exampleVariableOne
. This makes the new value for exampleVariableOne
60.
The "+=" and the "-=" functions add or subtract integers together before assigning them to the variable. Therefore, exampleVariableTwo += 5;
is actually the same as the statement exampleVariableTwo = exampleVariableTwo + 5;
. exampleVariableTwo
increases by a value of 3 as a result of the program because it adds 5 and subtracts 2 before printing.
Keep in mind that it is possible to also use "*=", "/=", or "%=" if you are comfortable with using these "shortcut" operators.