Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

++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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading