Incrementing or decrementing by one is a common task in programs. This task can be accomplished by the statements:
n = n + 1;
or n += 1;
Java also provides a unary operator called an increment operator, ++.
The statement n = n + 1
can be rewritten as ++n
. The following statements are equivalent:
n = n + 1; |
++n; |
sum = sum + 1; |
++sum; |
Java also provides for a decrement operator, --
, which decrements a value by one. The following are equivalent statements:
n = n - 1; |
--n; |
sum = sum - 1; |
--sum; |
- The increment and decrement operators can be written as either a prefix or postfix unary operator. If the
++
is placed before the variable it is called a pre-increment operator (++number
), but it can follow after the variable (number++
), which is called a post-increment operator. The following three statements have the same effect:
++number; number++; number = number + 1;
Before looking at the difference between prefix and postfix unary operators, it is important to remember Java operators solve problems and often return values. Just as the assignment operator (=) returns a value, the ++
and --
operators return values. Consider the following code fragments:
The statement b = ++a
uses the pre-increment operator. It increments the value of a
and returns the new value of a
.
The statement b = a++
uses the post-increment operator. It returns the value of a
and then increments a
by 1.
- The precedence and associativity of the unary increment and decrement operators is the same as the unary - operator.