00:00

Assignment Operators in Java – Explained with Examples

Assignment operators store values in variables. The basic one is =, and Java also offers compound assignment operators such as += and *=, which combine an operation with assignment in one short step.

This tutorial covers every assignment operator, the hidden cast inside compound assignments, chained assignments, using an assignment as an expression, and what assignment means for objects and arrays.

1. The Simple Assignment Operator =

= evaluates the expression on its right and stores the result in the variable on its left:

Simple assignment
int score = 0;          // initialise
score = 75;             // replace the value
score = score + 10;     // read, calculate, then store: 85
String name = "Asha";

The left side must be a variable (or an array element or field); 5 = x; is a compile error. Remember that = assigns, while == compares.

2. Compound Assignment Operators

OperatorExampleSame as
+=x += 5x = x + 5 (also appends to strings)
-=x -= 3x = x - 3
*=x *= 2x = x * 2
/=x /= 4x = x / 4
%=x %= 7x = x % 7
&=, |=, ^=f &= maskf = f & mask (bitwise)
<<=, >>=, >>>=f <<= 2f = f << 2 (shifts)
CompoundAssignment.java
public class CompoundAssignment {
    public static void main(String[] args) {
        int x = 20;
        System.out.println("x = 20");
        x += 5;  System.out.println("x += 5   -> " + x);
        x -= 3;  System.out.println("x -= 3   -> " + x);
        x *= 2;  System.out.println("x *= 2   -> " + x);
        x /= 4;  System.out.println("x /= 4   -> " + x);
        x %= 7;  System.out.println("x %= 7   -> " + x);

        int flags = 0b1100;
        flags &= 0b1010; System.out.println("flags &= 1010  -> " + Integer.toBinaryString(flags));
        flags |= 0b0001; System.out.println("flags |= 0001  -> " + Integer.toBinaryString(flags));
        flags ^= 0b1111; System.out.println("flags ^= 1111  -> " + Integer.toBinaryString(flags));
        flags <<= 2;     System.out.println("flags <<= 2    -> " + Integer.toBinaryString(flags));
        flags >>= 1;     System.out.println("flags >>= 1    -> " + Integer.toBinaryString(flags));

        String message = "Hello";
        message += ", Java";
        System.out.println(message);
    }
}
Output
x = 20
x += 5   -> 25
x -= 3   -> 22
x *= 2   -> 44
x /= 4   -> 11
x %= 7   -> 4
flags &= 1010  -> 1000
flags |= 0001  -> 1001
flags ^= 1111  -> 110
flags <<= 2    -> 11000
flags >>= 1    -> 1100
Hello, Java

3. The Hidden Cast in Compound Assignment

A compound assignment x op= y really means x = (Type of x) (x op y). That built-in cast makes some code compile that would otherwise fail, and it can also hide overflow or lost fractions:

ImplicitCast.java
public class ImplicitCast {
    public static void main(String[] args) {
        byte level = 10;
        // level = level + 5;     // compile error: possible lossy conversion from int to byte
        level += 5;               // OK: compound assignment casts automatically
        System.out.println("level = " + level);

        byte small = 120;
        small += 10;              // silently overflows past 127
        System.out.println("small = " + small);

        char letter = 'A';
        letter += 2;              // works on char too
        System.out.println("letter = " + letter);

        int total = 10;
        total += 2.9;             // the double result is cast back to int
        System.out.println("total = " + total);
    }
}
Output
level = 15
small = -126
letter = C
total = 12
  • level = level + 5 fails because level + 5 is an int; level += 5 compiles thanks to the cast.
  • small += 10 silently wraps from 130 to -126, because a byte can only hold up to 127.
  • total += 2.9 adds 2.9 and then truncates back to int, giving 12.

4. Chained Assignment and Assignment as an Expression

An assignment is itself an expression, and its value is the value that was assigned. Assignment is right-associative, so a = b = c = 5 works from right to left. The same property allows the common "read until end" loop:

AssignmentExpression.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class AssignmentExpression {
    public static void main(String[] args) throws IOException {
        // Chained assignment works right to left
        int a, b, c;
        a = b = c = 5;
        System.out.println("a=" + a + " b=" + b + " c=" + c);

        // An assignment is an expression whose value is the assigned value
        BufferedReader reader = new BufferedReader(new StringReader("first\nsecond\nthird"));
        String line;
        int count = 0;
        while ((line = reader.readLine()) != null) {     // assign, then test
            count++;
            System.out.println(count + ": " + line);
        }
    }
}
Output
a=5 b=5 c=5
1: first
2: second
3: third

The parentheses in (line = reader.readLine()) != null are required, because != has higher precedence than =.

5. Assigning References: Objects and Arrays

For object and array variables, = copies the reference, not the object. Both variables then refer to the same object, and a change through one is visible through the other:

ReferenceAssignment.java
import java.util.Arrays;

public class ReferenceAssignment {
    public static void main(String[] args) {
        int[] original = {1, 2, 3};
        int[] alias = original;               // copies the reference, not the array
        alias[0] = 99;
        System.out.println("original = " + Arrays.toString(original));

        int[] copy = original.clone();        // a real copy
        copy[1] = 42;
        System.out.println("original = " + Arrays.toString(original) + ", copy = " + Arrays.toString(copy));
    }
}
Output
original = [99, 2, 3]
original = [99, 2, 3], copy = [99, 42, 3]

To get an independent copy, use clone(), Arrays.copyOf(), a copy constructor or List.copyOf().

6. Assignment and final

A final variable can be assigned exactly once. Any further assignment, including compound ones such as MAX += 1, is a compile error. See final keyword in Java.

7. Using += with Strings

+= on a String creates a new string each time, because strings are immutable. That is fine for a few joins, but in large loops use a StringBuilder:

Building strings
// Fine for small amounts
String csv = "";
csv += "a,";
csv += "b";

// Better in loops
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append(i).append(',');
}
String result = sb.toString();

8. Common Mistakes

  • Writing if (x = 5) instead of if (x == 5). In Java this does not compile for int, but with boolean variables if (done = true) compiles and is always true.
  • Writing x =+ 5 (which assigns +5) instead of x += 5.
  • Relying on the hidden cast in += and missing an overflow.
  • Expecting b = a to copy an array or object.

9. Summary

  • = stores the value of the right side in the variable on the left.
  • Compound operators (+=, -=, *=, /=, %=, bitwise and shift variants) combine an operation with assignment.
  • Compound assignment includes an implicit cast to the variable's type.
  • Assignment is right-associative and is itself an expression.
  • Assigning an object or array copies the reference only.

Related Tutorials