Increment and Decrement Operators in Java
The increment and decrement unary operator in Java lets you increase or decrease the value of a variable by one. It can be a shorter notation than using the compound assignment operator. However, there are prefix and postfix forms that produce different results when used in expressions.
Ways to Increase a Number by One
Here are some ways to increase a number by one: writing out explicitly, using the compound assignment operator, and using the increment unary operator.
Writing out explicitly:
int number = 0;number = number + 1; // 1
Using the compound assignment operator:
int number = 0;number += 1;
Using the increment unary operator:
int number = 0;number++;ORint number = 0;++number;
Using the increment unary operator, we can achieve the same result as the ++
will add 1 to the value of the variable. If we want to subtract a value of a variable by 1, we would just use --
instead.
Pre-Increment and Post-Increment Unary Operators
As seen in the previous example, we can place the increment unary operator before of after the variable. Although this doesn't matter in the previous example, there are differences between the prefix and postfix form when using in an expression.
Using the prefix form is a pre-increment, meaning that we increase the value of the variable first and then use the new value in the expression.
int operand = 0;int number = ++operand + 5; // 6
Which is equivalent to:
int operand = 0;operand += 1;int number = operand + 5; // 6
Using the postfix form is a post-increment, meaning that we evaluate the expression first and then increase the value of the variable.
int operand = 0;int number = operand++ + 5; // 5
This is equivalent to:
int operand = 0;int number = operand + 5; // 5operand += 1;
Pre-Decrement and Post-Decrement
The same goes for the decrement unary operator. We could put the --
before or after the operand.
Using pre-decrement unary operator:
int operand = 1;int number = --operand + 5; // 5
Is equivalent to:
int operand = 1;operand -= 1;int number = operand + 5; // 5
Using post-decrement unary operator:
int operand = 1;int number = operand-- + 5; // 6
Is equivalent to:
int operand = 1;int number = operand + 5; // 6operand -= 1;
Conclusion
Using the increment and decrement unary operators is common in writing Java code. It's important to understand how the prefix and postfix forms work, however they are not used as often as it can make the code harder to read and understand.