Compound Assignment Operator in Java
In Java, assignment operator is used to assign values to a variable. In this section, we will discuss the compound assignment operators in Java.
Compound Assignment Operator
The compound assignment operator is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator. The specified operation is performed between the right operand and the left operand and the resultant assigned to the left operand. Generally, these operators are used to assign results in shorter syntax forms. In short, the compound assignment operator can be used in place of an assignment operator.
For example:
Let’s write the above statements using the compound assignment operator.
Using both assignment operators generates the same result.
Java supports the following assignment operators:
Catagories | Operator | Description | Example | Equivalent Expression |
---|---|---|---|---|
Compound Arithmetic Operators | += | It assigns the result of the addition. | count += 1 | count = count + 1 |
-= | It assigns the result of the subtraction. | count -= 2 | count = count – 2 | |
*= | It assigns the result of the multiplication. | price *= quantity | price = price * quantity | |
/= | It assigns the result of the division. | average /= number_of_terms | average = number_of_terms | |
%= | It assigns the result of the remainder of the division. | s %= 1000 | s = s % 1000 | |
Compound Bitwise Operators | <<= | It assigns the result of the signed left bit shift. | res <<= num | res = res << num |
>>= | It assigns the result of the signed right bit shift. | y >>= 1 | y = y >> 1 | |
&= | It assigns the result of the logical AND. | x &= 2 | x = x & 2 | |
^= | It assigns the result of the logical XOR. | a ^= b | a = a ^ b | |
|= | It assigns the result of the logical OR. | flag |= true | flag = flag | true | |
>>>= | It assigns the result of the unsigned right bit shift. | p >>>= 4 | p = p >>> 4 |
Using Compound Assignment Operator in a Java Program
CompoundAssignmentOperator.java
Output:
z = x + y = 38 z += x = 63 z -= x = 38 z *= x = 950 z /= x = 0 z %= x = 5 z <<= 2 = 10 z >>= 2 = 5 z >>= 2 = 2 z &= x = 0 z ^= x = 12 z |= x = 12 s>>>= 4 = 18