Search code examples
javaadditionpost-increment

Why post increment opertor failed to increment 'a' in this code?


package com;

public class Test {

    public static void main(String[] args)
    {
        int a= 11, b = 10;
        a = a++ + ++b;  //why? output is "22 11" and not "23 11"
        System.out.println(a+" "+b);

    }

}

Solution

  • Here's how the expression gets evaluated (roughly, I didn't check the JLS for evaluation order but I think it's from left to right):

    a = a++ + ++b;  // a is 11, b is 10
    a = 11 + ++b;  // a is 12 but its previous value 11 was returned by a++, b is 10
    a = 11 + 11;  // a is 12, b is 11 and its updated value was returned by ++b
    a = 22;  // a is 12, b is 11 and its updated value was returned by ++b
    

    Therefore, it's the expected result, you just have to apply the definition of those operators.