Reputation: 152
I have this code:
class Example {
public static void main(String args[]) {
int x = 99;
if (x++ == x) {
System.out.println("x++==x : " + x);
}
if (++x == x ) {
System.out.println("++x==x : " + x); // ++x == x : 101
}
if (x == x++) {
System.out.println("x==x++ : " + x); //x==x++ : 102
}
if (x == ++x) {
System.out.println("x==++x : " + x);
}
if (++x == ++x) {
System.out.println("++x==++x : " + x);
}
if (x++ == x++) {
System.out.println("x++==x++ : " + x);
}
if (++x == x++) {
System.out.println("++x==x++ : " + x); // ++x==x++ : 109
}
}
}
and this is the output -->
++x==x : 101
x==x++ : 102
++x==x++ : 109
I want to figure out how the java compiler handles this code. I could figure out how it came up with this part of the output:
++x==x : 101
x==x++ : 102
But I couldn't with this part of the output:
++x==x++ : 109
How does this code work? And most importantly how does the last output work?
Upvotes: 2
Views: 922
Reputation: 1066
++x
is pre-increment
x++
is post-increment
Even if your condition gets a false, the incrementing will be done.
Upvotes: 1
Reputation: 102795
You just need to know 3 things and use logic to put it together:
x++
means: "Increment x, but the expression's value is what x was before you increment".++x
means: "Increment x, and the expression's value is what x is after you increment".==
operator. So, java 'resolves' the thing on the left, then the thing on the right, then does the calculation.Thus, given: ++x==x++
, and let's say x
starts out as 107. Let's break it down:
++x
. To do that, increment (x
is now 108), then resolve the expression as the value after increment. So, the left hand side is 108
.x++
. To do that, increment (x
is now 109), then resolve the expression as the value before increment. So, the right hand side is 108
.108 == 108
. That's true
, so the if 'passes', and the result is printed. Given that x
is now 109, it would print "++x==x++ : 109".Which is exactly what it does.
Upvotes: 5