The left hand operand for these operators must be a 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 operands 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= E2is equivalent toE1 = (T) ((E1) op (E2)), whereTis the type ofE1, except thatE1is 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 + bwill add the value ofa + bto the value ofcand assign it toc
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 a "concatenate and assign" operator.
Example:
c += ais roughly the same asc = c + a
3. -=
The "subtract and assign" operator: subtracts the value of the right operand from the value of the left hand operand and assign the result to left hand operand.
Example:
c -= ais roughly the same asc = 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 assign the result to left hand operand. .
Example:
c *= ais roughly the same asc = c * a
5. /=
The "divide and assign" operator: divides the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand.
Example:
c /*= ais roughly the same asc = c / a
6. %=
The "modulus and assign" operator: calculates the modulus of the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand.
Example:
c %*= ais roughly the same asc = c % a
7. <<=
The "left shift and assign" operator.
Example:
c <<= 2is roughly the same asc = c << 2
8. >>=
The "arithmetic right shift and assign" operator.
Example:
c >>= 2is roughly the same asc = c >> 2
9. >>>=
The "logical right shift and assign" operator.
Example:
c >>>= 2is roughly the same asc = c >>> 2
10. &=
The "bitwise and and assign" operator.
Example:
c &= 2is roughly the same asc = c & 2
11. |=
The "bitwise or and assign" operator.
Example:
c |= 2is roughly the same asc = c | 2
12. ^=
The "bitwise exclusive or and assign" operator.
Example:
c ^= 2is roughly the same asc = c ^ 2