Assignment Operators

Compound Assignment

OperatorSame as
x = 5assign 5
x += 3x = x + 3
x -= 3x = x - 3
x *= 3x = x * 3
x /= 3x = x / 3
x %= 3x = x % 3

Example

public class Main {
    public static void main(String[] args) {
        int wallet = 1000;
        wallet += 500;   // add money
        System.out.println(wallet);
        wallet -= 300;   // pay a bill
        System.out.println(wallet);
        wallet *= 2;     // double cashback offer
        System.out.println(wallet);
        wallet /= 4;
        System.out.println(wallet);
        wallet %= 7;
        System.out.println(wallet);
    }
}

Output

1500
1200
2400
600
5

Hidden Cast

Example

Compound operators include an automatic cast. x = x + 1.5 would not compile for an int x, but x += 1.5 does (and drops the decimals).

public class Main {
    public static void main(String[] args) {
        int x = 10;
        x += 1.7;      // same as x = (int) (x + 1.7)
        System.out.println(x);
    }
}

Output

11