The Assignment Operators - and
suggest changeThe left hand operand for these operators must be either a non-final variable or an element of an array. The right hand operand must be assignment compatible with the left hand operand. This means that either the types must be the same, or the right operand type must be convertible to the left operand's type by a combination of boxing, unboxing or widening. (For complete details refer to JLS 5.2.)
The precise meaning of the “operation and assign” operators is specified by JLS 15.26.2 as:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
Note that there is an implicit type-cast before the final assignment.
\1. =
The simple assignment operator: assigns the value of the right hand operand to the left hand operand.
Example: c = a + b assigns the value of a + b to c
\2. +=
The “add and assign” operator: adds the value of right hand operand to the value of the left hand operand and assigns the result to left hand operand. If the left hand operand has type String, then this is a “concatenate and assign” operator.
Example: c += a is roughly the same as c = c + a
\3. -=
The “subtract and assign” operator: subtracts the value of the right operand from the value of the left hand operand and assigns the result to the left hand operand.
Example: c -= a is roughly the same as c = c - a
\4. *=
The “multiply and assign” operator: multiplies the value of the right hand operand by the value of the left hand operand and assigns the result to the left hand operand.
Example: c *= a is roughly the same as c = c * a
\5. /=
The “divide and assign” operator: divides the value of the left hand operand by the value of the right hand operand and assigns the result to the left hand operand.
Example: c /*= a is roughly the same as c = c / a
\6. %=
The “modulus and assign” operator: calculates the remainder when the left hand operand is divided by the right hand operand and assigns the result to the left hand operand.
Example: c %*= a is roughly the same as c = c % a
\7. <<=
The “left shift and assign” operator.
Example: c <<= 2 is roughly the same as c = c << 2
\8. >>=
The “arithmetic right shift and assign” operator.
Example: c >>= 2 is roughly the same as c = c >> 2
\9. >>>=
The “logical right shift and assign” operator.
Example: c >>>= 2 is roughly the same as c = c >>> 2
\10. &=
The “bitwise and and assign” operator.
Example: c &= 2 is roughly the same as c = c & 2
\11. |=
The “bitwise or and assign” operator.
Example: c |= 2 is roughly the same as c = c | 2
\12. ^=
The “bitwise exclusive or and assign” operator.
Example: c ^= 2 is roughly the same as c = c ^ 2