Java Assignment Operators

Assignment operators put values into variables. The plain equals sign is the one you use most, but Java also offers a family of compound operators that update a variable using its current value, keeping your code short and clear.

The basic assignment operator

The single equals sign takes the value on its right and stores it in the variable on its left. It is important not to confuse this with the double equals used for comparison; a single = always means assign, never compare.

Assigning and reassigning

public class Main {
  public static void main(String[] args) {
    int level = 1;   // store 1 in level
    level = 5;       // replace it with 5
    level = level + 2; // read level (5), add 2, store back 7

    System.out.println(level); // 7
  }
}

Compound assignment operators

Writing level = level + 2 is a little repetitive. Java lets you shorten it to level += 2. Every arithmetic operator has a compound partner that does the maths and stores the result in one step.

OperatorExampleSame asMeaning
+=x += 4x = x + 4add then store
-=x -= 4x = x - 4subtract then store
*=x *= 4x = x * 4multiply then store
/=x /= 4x = x / 4divide then store
%=x %= 4x = x % 4remainder then store

Compound operators in practice

Watch how a single variable changes as we apply several compound operators in a row. Each one uses the current value of total to produce the next value.

Updating a running total

public class Main {
  public static void main(String[] args) {
    int total = 10;

    total += 5;  // 15
    total -= 3;  // 12
    total *= 2;  // 24
    total /= 4;  // 6

    System.out.println(total); // 6
  }
}
Note: The += operator also works with strings. Starting from String s = "Hi"; then s += " there"; leaves s holding "Hi there". This is handy for building up text piece by piece.

Building a string with +=

public class Main {
  public static void main(String[] args) {
    String message = "Java";
    message += " is";
    message += " fun";

    System.out.println(message); // Java is fun
  }
}
Note: A single = inside an if condition is a classic mistake. if (x = 5) assigns rather than compares and will not compile for numbers. Use == to test for equality.