Assignment Operators


Assignment Operators

🙋 Need help? Ask an expert now!

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;

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.

Edit Me on GitHub!

Application Question

What is the new value of varOne after the following code is executed?

int varOne = 12;
varOne += 5;
varOne -= 10;
varOne = 12;