How to Use Compound Assignment Operators in Java - dummies

How to Use Compound Assignment Operators in Java

By Doug Lowe

A compound assignment operator is an operator that performs a calculation and an assignment at the same time. All of Java’s binary arithmetic operators (that is, the ones that work on two operands) have equivalent compound assignment operators.

Compound Arithmetic Operators in Java
Operator Description
+= Addition and assignment
-= Subtraction and assignment
*= Multiplication and assignment
/= Division and assignment
%= Remainder and assignment

The statement

a += 10;

is equivalent to

a = a + 10;

Also, the statement

z *=2;

is equivalent to

z = z * 2;

To prevent confusion, use compound assignment expressions by themselves, not in combination with other expressions. Consider these statements:

int a = 2;

int b = 3;

a *= b + 1;

Is a set to 7 or 8?

In other words, is the third statement equivalent to

a = a * b + 1; // This would give 7 as the result


a = a * (b + 1); // This would give 8 as the result

At first glance, you might expect the answer to be 7, because multiplication has a higher precedence than addition. But assignment has the lowest precedence of all, and the multiplication here is performed as part of the assignment. As a result, the addition is performed before the multiplication — and the answer is 8. (Gotcha!)