Arithmetic Compound Assignment Operators In Java are used to combine an arithmetic operation with an assignment operation. e.g., marks += 5;
instead of marks = marks + 5;
Compound assignment operators provide a shorter syntax for assigning the result of an arithmetic operator.
If the we want to multiply a variable
score
by 3 and assign it to the same variable
score
, we could use
score *= 3;
instead of using
score = score * 3;
The general syntax of the compound assignment operators is
var op= expression;
- Compound assignment is supported for addition, subtraction, multiplication, division and modulus and the corresponding operators respectively are
+=, -=, *=, /=, %=
- Compound assignment operators are faster than performing the operation and then assigning. i.e. doing
score *= 3;
is faster than score = score * 3;
Compound Assignment Operators
class CompoundAssignments
{
public static void main(String arg[])
{
int x = 5;
int y = 2;
int z = 3;
x += 6; // LINE A
y *= 8; // LINE B
z += y * x; // LINE C
z %= 7; // LINE D
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
}
DESCRIPTIONHere, we have declared three variables x
, y
and z
and initialized them.
In LINE A
, 6
is added to previous x
value, which is 5
and assigned to x
again. So x
becomes 11 (= 5 + 6)
.
In LINE B
, the value of y
is changed to 16 (= 8 * 2)
from 2
.
In LINE C
, the y * x (= 16 * 11 = 176)
is added to z
and assigned to z
again. So z
changes from 3
to 179 (= 176 + 3)
.
In LINE D
, the value of z % 7
is assigned to z
, so z
becomes 4 (= 179 % 7)
.
THINGS TO TRY
- Change the order of the lines
A, B, C
and D
to B, A, D
and C
and see what will be the output. Try some other order of lines and check if the output is per your understanding.
- Change the order of the lines such that the
x
is 11
, y
is 16
and z
is 25
at the end of the program.
- Try other operators like
-=
and /=
.
2-min video about compound assignment operators