In Java, the +=
operator is used to add a value to a variable and assign the result back to the same variable. For example:
int x = 5; x += 2; // x is now 7
This is equivalent to writing:
int x = 5; x = x + 2; // x is now 7
The +=
operator can be used with any primitive data type (such as int
, float
, double
, etc.) or with objects that support the +
operator. For example:
String s = "Hello"; s += " World"; // s is now "Hello World"
You can also use the -=
, *=
, and /=
operators to subtract, multiply, or divide a value from a variable, respectively. For example:
int x = 10; x /= 2; // x is now 5
This is equivalent to writing:
int x = 10; x = x / 2; // x is now 5