I have the following code:
public class Tests {
public static void main(String[] args) throws Exception {
int x = 0;
while(x<3) {
x = x++;
System.out.println(x);
}
}
}
We know he should have writen just x++
or x=x+1
, but on x = x++
it should first attribute x
to itself, and later increment it. Why does x
continue with 0
as value?
--update
Here's the bytecode:
public class Tests extends java.lang.Object{
public Tests();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]) throws java.lang.Exception;
Code:
0: iconst_0
1: istore_1
2: iload_1
3: iconst_3
4: if_icmpge 22
7: iload_1
8: iinc 1, 1
11: istore_1
12: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
15: iload_1
16: invokevirtual #3; //Method java/io/PrintStream.println:(I)V
19: goto 2
22: return
}
I'll read about the instructions to try to understand...
I think because in Java ++ has a higher precedence than = (assignment)...Does it? Look at http://www.cs.uwf.edu/~eelsheik/cop2253/resources/op_precedence.html...
The same way if you write x=x+1...+ has a higher precedence than = (assignment)
Before incrementing the value by one, the value is assigned to the variable.
The
x++
expression evaluates tox
. The++
part affect the value after the evaluation, not after the statement. sox = x++
is effectively translated intoYou're effectively getting the following behavior.
The idea being that the post-increment operator (x++) increments that variable in question AFTER returning its value for use in the equation it's used in.
Edit: Adding a slight bit because of the comment. Consider it like the following.
From http://download.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
To illustrate, try the following:
Which will print 1 and 0.
because of above statement x never reaches 3;