Java Reference
In-Depth Information
Suppose you declare an
int
variable called
i
.
int i = 100;
To increment the value of
i
by
1
, you can use one of the four following expressions:
i = i + 1; // Assigns 101 to i
i += 1; // Assigns 101 to i
i++; // Assigns 101 to i
++i;
The increment operator ++ can also be used in a more complex expression as
int i = 100;
int j = 50;
j = i++ + 15; // Assigns 115 to j and i becomes 101
The expression
i++ + 15
is evaluated as follows:
i
is evaluated and the right-hand expression becomes
100 + 15
.
•
The value of
i
in memory is incremented by
1
. So, at this stage the value of the variable
i
in
memory is
101
.
•
The value of
•
The expression 100 + 15 is evaluated and the result 115 is assigned to j.
There are two kinds of increment operators:
•
Post-fix increment operator, for example, i++
•
When
++
appears after its operand, it is called a post-fix increment operator. When ++ appears before its operand,
it is called a pre-fix increment operator. The only difference in post-fix and pre-fix increment operators is the order in
which it uses the current value of its operand and the increment in its operand's value. The post-fix increment uses
the current value of its operand first, and then increments the operand's value, as you saw in the expression
j = i++ + 15
. Because
i++
uses a post-fix increment operator, first the current value of
i
is used to compute the value
of expression
i++ + 15 (e.g. 100 + 15)
. The value assigned to
j
is
115
. And then the value of
i
is incremented by
1
.
The result would be different if the above expression is rewritten using a pre-fix increment operator.
Pre-fix increment operator, for example, ++i
int i = 100;
int j = 50;
j = ++i + 15; // i becomes 101 and assigns 116 to j
In this case, the expression
++i + 15
is evaluated as follows:
++i
uses a pre-fix increment operator, first the value of
i
is incremented in memory
by
1
. Therefore, the value of
i
is
101
.
•
Because
i
, which is
101
, is used in the expression and the expression becomes
•
The current value of
101 + 15
.
101 + 15
is evaluated and the result
116
is assigned to
j
.
•
The expression
Note that after evaluation of both expressions
i++ + 15
and
++i + 15
, the value of
i
is the same, which is
101
.
However, the values assigned to
j
differ. If you are using the increment operator ++ in a simple expression as in
i++
or
++i
, you cannot observe any difference in using a post-fix or pre-fix operator.