Search code examples
javaunary-operatorexpression-evaluation

++i+i++ evaluation


Confusion rose because of this post. The author updated his post, and the result became clear. Conclusion: Java evaluates expressions from left to right

Closed!

As evaluation of expression is done from right to left the following code should store 5 in j:

int i=2;
int j=++i+i++;
System.out.println(j);

But I get 6 as the output, which forces me to re-think the right to left evaluation idea. Kindly explain the theory here.


Solution

  • int i = 2;
    int j = ++i + i++;
    

    is the same as

    int i = 2;
    
    // This part is from ++i
    i = i + 1;
    int left = i; // 3
    
    // This part is from i++
    int right = i; // 3
    i = i + 1;
    
    int j = left + right; // 3 + 3 = 6
    

    If instead you'd done:

    int i = 2;
    int j = i++ + ++i;
    

    that would be equivalent to:

    int i = 2;
    
    // This part is from i++
    int left = i; // 2
    i = i + 1;
    
    // This part is from ++i
    i = i + 1;
    int right = i; // 4
    
    
    int j = left + right; // 2 + 4 = 6
    

    So the sum is the same, but the terms being summed are different.