Java Reference
In-Depth Information
Operator
name
Sample
expression
Operator
Explanation
prefix
increment
++a
Increment a by 1 , then use the new value
of a in the expression in which a resides.
++
a++
++
postfix
increment
Use the current value of a in the expression
in which a resides, then increment a by 1 .
--b
--
prefix
decrement
Decrement b by 1 , then use the new value
of b in the expression in which b resides.
b--
--
postfix
decrement
Use the current value of b in the expression
in which b resides, then decrement b by 1 .
Fig. 4.14 | Increment and decrement operators.
Using the prefix increment (or decrement) operator to add 1 to (or subtract 1 from)
a variable is known as preincrementing (or predecrementing ). This causes the variable to
be incremented (decremented) by 1; then the new value of the variable is used in the
expression in which it appears. Using the postfix increment (or decrement) operator to add
1 to (or subtract 1 from) a variable is known as postincrementing (or postdecrementing ).
This causes the current value of the variable to be used in the expression in which it
appears; then the variable's value is incremented (decremented) by 1.
Good Programming Practice 4.4
Unlike binary operators, the unary increment and decrement operators should be placed
next to their operands, with no intervening spaces.
Difference Between Prefix Increment and Postfix Increment Operators
Figure 4.15 demonstrates the difference between the prefix increment and postfix incre-
ment versions of the ++ increment operator. The decrement operator ( -- ) works similarly.
Line 9 initializes the variable c to 5 , and line 10 outputs c 's initial value. Line 11 out-
puts the value of the expression c++ . This expression postincrements the variable c , so c 's
original value ( 5 ) is output, then c 's value is incremented (to 6). Thus, line 11 outputs c 's
initial value ( 5 ) again. Line 12 outputs c 's new value ( 6 ) to prove that the variable's value
was indeed incremented in line 11.
Line 17 resets c 's value to 5 , and line 18 outputs c 's value. Line 19 outputs the value
of the expression ++c . This expression preincrements c , so its value is incremented; then
the new value ( 6 ) is output. Line 20 outputs c 's value again to show that the value of c is
still 6 after line 19 executes.
1
// Fig. 4.15: Increment.java
2
// Prefix increment and postfix increment operators.
3
4
public class Increment
5
{
Fig. 4.15 | Prefix increment and postfix increment operators. (Part 1 of 2.)
 
Search WWH ::




Custom Search