Java Reference
In-Depth Information
decrement the value of the variable by
1
. What is the difference between the pre and post
forms of these operators? The difference becomes apparent when the variable using these
operators is employed in an expression.
Suppose that
x
is a variable of type
int
.If
++x
is used in an expression, first the value of
x
is incremented by
1
, and then the new value of
x
is used to evaluate the expression. On
the other hand, if
x++
is used in an expression, first the current value of
x
is used in the
expression, and then the value of x is incremented by
1
. The following example clarifies
the difference between the pre- and post-increment operators.
Suppose that
x
and
y
are
int
variables. Consider the following statements:
2
x = 5;
y = ++x;
The first statement assigns the value
5
to
x
. To evaluate the second statement, which uses
the pre-increment operator, first the value of
x
is incremented to
6
, and then this value,
6
, is assigned to
y
. After the second statement executes, both
x
and
y
have the value
6
.
Now consider the following statements:
x = 5;
y = x++;
As before, the first statement assigns
5
to
x
. In the second statement, the post-increment
operator is applied to
x
. To execute the second statement, first the value of
x
, which is
5
,
is used to evaluate the expression, and then the value of
x
is incremented to
6
. Finally, the
value of the expression, which is
5
, is stored in
y
. After the second statement executes,
the value of
x
is
6
and the value of
y
is
5
.
The following example further illustrates how the pre- and post-increment operators work.
EXAMPLE 2-19
Suppose
a
and
b
are
int
variables and:
a = 5;
b = 2 + (++a);
The first statement assigns
5
to
a
. To execute the second statement, first the expression
2 + (++a
) is evaluated. As the pre-increment operator is applied to
a
, first the value of
a
is
incremented to
6
. Then,
2
is added to
6
to get
8
, which is then assigned to
b
. Therefore,
after the second statement executes,
a
is
6
and
b
is
8
. On the other hand, after the
execution of:
a = 5;
b = 2 + (a++);
the value of
a
is
6
while the value of
b
is
7
.
Search WWH ::
Custom Search