In some of the earlier lessons, we went over some of the different math operators. In the chart below, it shows the most common math operators we use in Java.
In this lesson, we are going to learn about a shortcut that can be used to cut back on syntax. For simplicity’s sake, we will start with addition.
Let’s say that we had an
int i = 1 in our program, and that we want to add 5 to i. Based on what we have gone over, we would put something like the following:
The output would be 6 because int i is equal to 1, and then we add our value of i to 5 to get 6. Now, let’s look at the code below to see how it would look if we had used a compound assignment operator.
See the difference? Instead of the
i = i + 5, we simply replace it with
i += 5 and it gives us the exact same answer of 6.
The important thing to note is that the first coding example does the exact same thing as the second coding example. The only difference between the two is the syntax. One is not necessarily better than the other. It is just a simple way that some people prefer to shorten their code. Look at the chart below to see how addition, subtraction, multiplication, and division would be written in a compound assignment operator’s form.
|Equation Type||Compound Assignment Operator|
|Add and equal to||+=|
|Subtract and equal to||-=|
|Multiply and equal to||*=|
|Divide and equal to||/=|
Even if you find yourself sticking to the way you originally learned, do not worry about it. I still find myself trying to avoid using compound assignment operators and the minor complications that can arise from using them. However, it is still important to know and recognize them when we are looking over other programmer’s code.