In Java, the += operator is used to add a value to a variable and assign the result to that variable. This is known as an augmented assignment operator.
For example, consider the following code:
int x = 5;
x += 3;
In this code, the value of x
is first set to 5. Then, the value of x
is increased by 3 using the += operator. The final value of x
is 8.
The += operator can be used with any primitive data type or object that has a corresponding compound assignment operator. For example, you can use += with integers, doubles, strings, and even arrays.
Here are some examples of using the += operator with different data types:
// Add two integers and assign the result to an integer variable
int x = 5;
int y = 3;
x += y; // x is now 8
// Concatenate two strings and assign the result to a string variable
String s1 = "Hello";
String s2 = "World";
s1 += s2; // s1 is now "HelloWorld"
// Add two doubles and assign the result to a double variable
double d1 = 5.5;
double d2 = 3.2;
d1 += d2; // d1 is now 8.7