Use of += Addition Assignment Operator in Java
In this tutorial, we are learning how to use and what operations can be done with += operator in Java. In a programming language, x+=y is the same as using x=x+y. += operator is called a compound assignment operator. Compound assignment operators are shortcuts that do a math operation and assignment in a single step.
We can use += operator to increment variables and concatenate strings.
Using += operator to increment values in Java
Let’s see how we can use the += operator in incrementing values.
int a=20; a+=10; System.out.println(a);
I have initialized a variable ‘a’ with the value ’20’ which is an Integer type, then with the help of the += operator I have incremented it by ’10’.So the output is:
30
Using += operator to concatenate strings
Let’s see how we concatenate using the += operator.
String b="Hello"; b+="World"; System.out.println(b);
I have initialized a String with the name ‘b’ and assigned value as ‘Hello’, then I have concatenated it ‘World’ using the += operator. So the output looks like this:
HelloWorld
The following is the list of all possible compound assignment operators in Java.
- +=
- -=
- *=
- /=
- %=
Similarly, for the bitwise operator, we have the compound assignment
- &=
- |=
- ^=
Also read: Minimum delete operations to make all elements of array same in Java
Leave a Reply