Augmented Assignment Operators

paulike

Paul Ngugi

Posted on April 24, 2024

Augmented Assignment Operators

The operators +, -, **, */, and % can be combined with the assignment operator to form augmented operators. Very often the current value of a variable is used, modified, and then reassigned back to the same variable. For example, the following statement increases the variable count by 1:

count = count + 1;
Enter fullscreen mode Exit fullscreen mode

Java allows you to combine assignment and addition operators using an augmented (or compound) assignment operator. For example, the preceding statement can be written as

count += 1;

Enter fullscreen mode Exit fullscreen mode

The += is called the addition assignment operator. More are -=, **=, */=, and **%=.
The augmented assignment operator is performed last after all the other operators in the expression are evaluated. For example,

x /= 4 + 5.5 * 1.5;

Enter fullscreen mode Exit fullscreen mode

is same as

x = x / (4 + 5.5 * 1.5);
Enter fullscreen mode Exit fullscreen mode

There are no spaces in the augmented assignment operators. For example, + = should be +=

Like the assignment operator (=), the operators (+=, -=, **=, */=, **%=) can be used to form an assignment statement as well as an expression. For example, in the following code, x += 2 is a statement in the first line and an expression in the second line.

x += 2; // Statement
System.out.println(x += 2); // Expression
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
paulike
Paul Ngugi

Posted on April 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Augmented Assignment Operators
java Augmented Assignment Operators

April 24, 2024

Numeric Literals
java Numeric Literals

April 24, 2024

Named Constants
java Named Constants

April 24, 2024

Programming Errors
java Programming Errors

April 22, 2024