Java Reference
In-Depth Information
Here is a puzzle for Java beginners. The puzzle includes the use of the increment operator as follows:
int i = 15;
i = i++; // What will be the value of i after this assignment?
What will be the value of
i
after
i = i++
is executed? If your guess is 16, you are wrong. Here is the explanation of
how the expression is evaluated.
•
i++
is evaluated. Because
i++
uses a post-fix increment operator, the current value of
i
is used
in the expression. The current value of
i
is
15
. The expression becomes
i = 15
.
The value of
•
i
is incremented by
1
in memory as the second effect of
i++
. At this point, the
value of
i
is
16
in memory.
The expression
i = 15
is evaluated and the value
15
is assigned to
i
. The value of the variable
i
in memory is
15
and that is the final value. In fact, variable
i
observed a value 16 in the
previous step, but this step overwrote that value with 15. Therefore, the final value of the
variable
i
after
i = i++
is executed will be
15
,
not 16
.
In the above example, the order of operations is important. It is important to note that in case of
i++
the value
of the variable
i
is incremented as soon as the current value of
i
is used in the expression. To make this point clearer,
consider the following example:
•
int i = 10;
i = i++ + i; // Assigns 21 to i
i = 10;
i = ++i + i++; // Assigns 22 to i
There are also post-fix and pre-fix decrement operators (e.g.
i--
,
--i
). The following are examples of using
post-fix and pre-fix decrement operators:
int i = 15;
int j = 16;
i--;
--i;
i = 10;
i = i--; // Assigns 10 to i
i = 10;
j = i-- + 10; // Assigns 20 to j and 9 to i
i = 10;
j = --i + 10; // Assigns 19 to j and 9 to i
There are two important points to remember about the use of increment and decrement operators.
•
The operand of the increment and decrement operators must be a variable. For example, the
expression
5++
is incorrect because
++
is being used with a constant.
++
or
--
operator is a value, not a variable. For example,
i++
evaluates to a value, so you cannot use
i++
as the left-hand of an assignment operator or
where a variable is required.
•
The result of the expression using