+= -= *= /=
Performs an operation and stores the result back in the same variable.
Available since: Java 1.0
Syntax
x += valueExamples
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, AnnaA 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:
12Notes
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
- ++ / -- — Increases or decreases a variable by one.
- StringBuilder.append() — Adds a value to the end of a StringBuilder.
Related recipes
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.