GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes ? i=++i ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "? i=++i ?" Watch "? i=++i ?" New topic
Author

? i=++i ?

Roger Zhao
Ranch Hand

Joined: Aug 05, 2003
Posts: 73
Hi, all:
public class test {
public static void main(String args[]) {
int i=0, j=2;
do {
i=++i;
j--;
} while(j>0);
System.out.println(i);
}
}
output is 0.
Why? What happened on i=++i?
Thanks
Roger


"There is a will,there is a way!"<br />SCJP1.4
Dan Lastoria
Ranch Hand

Joined: Jan 30, 2002
Posts: 57
The output is actually 2, not 0.
Maybe you printed out j by accident?
[ August 19, 2003: Message edited by: Dan Lastoria ]
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
If the ++i is changed to i++, then the output is indeed 0. Roger, did you post the example code correctly?


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Dan Lastoria
Ranch Hand

Joined: Jan 30, 2002
Posts: 57
If the statement was this instead:
i = i++;
Then that makes sense...it's just a matter of operator precedence. The last thing this statement actually does is set i to the pre-incremented value of i++. The actual value of i is then 0.
In other words:
i on the right hand side evaluates to 0 during this expression. It is not incremented until after the expression completes.
However the = operator has a lower precedence than the ++ operator.
So the ++ changes i = 1
But then the = operator assigns i = 0, the value that i is throughout the expression. Remember it doesn't get incremented until after the expression is completed. However the increment is lost since you performed an assignment (lower precedence).
Confusing, I know. Hard for me to explain. That's why I rarely use postfix or prefix increments within expressions. I typically use them "stand-alone".
Dan Lastoria
Ranch Hand

Joined: Jan 30, 2002
Posts: 57
Looking at this might help too:

This snippet will print:
m is: 5
k is: 6
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
To repeat myself and others from previous conversations on similar topics, the real lesson here shouldn't be to understand exactly what happens in statements such as i = ++i or i = i++, but to learn to not write code in such a manner. Code should be clear to the humans that read it.
 
GeeCON Prague 2014
 
subject: ? i=++i ?