Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

+= -= *= /=

Performs an operation and stores the result back in the same variable.

Available since: Java 1.0

Syntax

x += value

Examples

A shorthand for x = x + 5:

void main() {
    int total = 10;
    total += 5;
    total *= 2;
    total -= 6;
    total /= 4;
    IO.println(total);
 
    String s = "Hi";
    s += ", Anna";
    IO.println(s);
}

Output:

6
Hi, Anna

A hidden type cast:

void main() {
    int count = 10;
    count += 2.7;
    // count = count + 2.7;  // error: incompatible types: possible lossy conversion from double to int
    IO.println(count);
}

Output:

12

Notes

x += y means x = (type of x)(x + y): the result is silently cast to the variable's type, so the fractional part can be lost. For int, /= is integer division. For strings, += in a long loop is slow — use StringBuilder.

See also

Related recipes

In the tutorial

  • Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.

Thanks for reading!

Donate to the site — we work hard for you.