Madhura
Madhura

Reputation: 152

How increment and decrement with if condition

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

Answers (2)

robni
robni

Reputation: 1066

++x is pre-increment x++ is post-increment

Even if your condition gets a false, the incrementing will be done.

Upvotes: 1

rzwitserloot
rzwitserloot

Reputation: 102795

You just need to know 3 things and use logic to put it together:

  1. x++ means: "Increment x, but the expression's value is what x was before you increment".
  2. ++x means: "Increment x, and the expression's value is what x is after you increment".
  3. Things resolve left to right for the == 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:

  1. First, resolve the left side, which is ++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.
  2. Next resolve right side, which is 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.
  3. Now do the operation. 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

Related Questions