Java Reference
In-Depth Information
yield the following output:
The value of n is changed to 2
The value of m is changed to 6
An expression like n++ also evaluates to a number as well as changing the value of
the variable n , so n++ can be used in an arithmetic expression such as
2*(n++)
The expression n++ changes the value of n by adding one to it, but it evaluates to the
value n had before it was increased. For example, consider the following code:
int n = 2;
int valueProduced = 2*(n++);
System.out.println(valueProduced);
System.out.println(n);
This code produces the following output:
4
3
Notice the expression 2*(n++) . When Java evaluates this expression, it uses the value
that number has before it is incremented, not the value that it has after it is incre-
mented. Thus, the value produced by the expression n++ is 2 , even though the incre-
ment operator changes the value of n to 3 . This may seem strange, but sometimes it is
just what you want. And, as you are about to see, if you want an expression that
behaves differently, you can have it.
The expression ++n also increments the value of the variable n by one, but it evalu-
ates to the value n has after it is increased. For example, consider the following code:
int n = 2;
int valueProduced = 2*(++n);
System.out.println(valueProduced);
System.out.println(n);
This code is the same as the previous piece of code except that the ++ is before the vari-
able, so this code will produce the following output:
6
3
Notice that the two increment operators n++ and ++n have the exact same effect on
a variable n : they both increase the value of n by one. But the two expressions evaluate
to different values. Remember, if the ++ is before the variable, then the incrementing is
done before the value is returned; if the ++ is after the variable, then the incrementing
is done after the value is returned.
v++ versus ++v
Search WWH ::




Custom Search