Increment Assign Operator

A very common operation that we do with integer variables, is to add value to it. For example, if we want to add the value 5 to an existing variable a, we do the following statement: a = a+ 5. But since this is very common, Java made a short hand notation to make this even shorter. In this post, we will show examples on how to perform Increment Assign Operator to an integer variable.

Increment Assign With Literal

The Increment Assign Operator means to increment a variable's value by some expression, and then assign it back to the variable. That is the reason it is called increment assign, as the two steps are to increment and then assign. The operator used for this is denoted by the += symbol. this designate an increment assign operation. Below is a simple example in action:
int a = 15;
a += 4;
So we start with the variable a having the value of 15. So the question is, we want to add the value of 4 to a. So the statement a+= 4 is making the original value of a, which is 15, increment by 4 that results to the below output:

Increment Assign With Another variable

We are not limited to increment a variable with a literal integer value. We can also increment it with the value coming from another variable. For example:

int a = 20;
int b = 10;
a += b;

So in this example, a have the value of 20 while b has the value of 10. The sum of a and b is stored to the variable a, due to the increment assign operator used. Hence we get below output:

Increment Assign With An Expression

Actually, we can have any expression to the right side of an increment assign operator, and Java virtual machine will evaluate it, add to the original variable, and assign back. For example:
int a = 12;
int b = 3;
a += b * 5;
So in this example, the expression on the right side is evaluated first. So b, which has the value of 3 is multiplied by 5, giving the answer 15. Then that answer is added to the value of variable a. Hence we get below answer: