Java Reference
In-Depth Information
Figure 2.6
Output of the ArithmeticDemo program.
Increment and Decrement Operators
The increment operator ++ adds one to a number, and the decrement operator
- - subtracts one from a variable. The two operators are applied as either a
prefix or a suffix to any variable that represents a number.
Using these operators as a prefix is referred to as preincrement and pre-
decrement, and this causes the increment or decrement to occur immediately,
using the new value in the statement.
Using these operators as a suffix to a variable is referred to postincrement
and postdecrement, and this causes the increment or decrement to occur after
the variable is used in the statement. The variable is then incremented or
decremented after the statement.
For example, in the ArithmeticDemo program, x is assigned the value 5 and
then the following statement occurs:
y = x++;
This is a postincrement, so x gets incremented to 6 after it is used in the state-
ment. Therefore, y is 5 after this statement and x is 6.
The variable x is then assigned to 5 again, then you see the following
statement:
z = ++x;
This is a preincrement, so x becomes 6 before it is used in the statement.
Therefore, z will be 6, as you can see in the output of the ArithmeticDemo
program in Figure 2.6.
Search WWH ::




Custom Search