Using the Compound Assignment Operator
In cases where you are assigning a variable to a value that is the result of this value and an arithmetic operator, a compound assignment operator can be used. These operators are not required, but offer a short-cut to writing out these types of expressions. The compound operators are as follows:
+=is used to assign the variable to the sum of its value and another value.-=is used to assign the variable to the difference of its value and another value.*=is used to assign the variable to the producto of its value and another value./=is used to assign the variable to the quotient of its value and another value.%=is used to assign the variable to the remainder of its value and another value.++is used to add 1 to the value of the variable.
Your Turn
Let's try this in the Java Playground.
- The addition example has been provided for you.
- Modify the code to use the compound operators where possible.