What are Compound Assignment Operators in Java and Why You Should Use Them
Compound assignment operators are commonly used as they require less code to type. It's a shorter syntax of assigning the result of an arithmetic or bitwise operator, given that the variable to store the expression value is being used as an operand.
Compound Assignment Operator using Addition
Consider an example where we want to increase a given number by 3. The long version can be written as follows:
int number = 5;number = number + 3; // 8
The number
variable is used as the variable to store the expression value and as an operand. Because of this, we can use a shorter syntax of compound assignment operators. The code can be written as:
int number = 5;number += 3; // 8
Let's see another example using string concatenation:
String message = "Hello";message = message + " World"; // "Hello World"
Using compound assignment operators, this can be condensed to:
String message = "Hello";message += " World"; // "Hello World"
Compound Assignment Operator using Subtraction
As another example, let's see how we can decrease a number by 3:
int number = 5;number = number - 3; // 2
Again, since number
is used as the variable to store the expression value and an operand, we can use the compound assignment operator:
int number = 5;number -= 3; // 2
Conclusion
All arithmetic and bitwise operators can be used in compound assignment operators. This post shows examples using addition and subtraction to show the general syntax. Division, multiplication, modulus, AND, OR, XOR,left shift, right shift, and unsigned right shift would also work. Overall, using the compound assignment operator requires less code to type and is more common to see code written this way.