Search code examples
javaoperatorsincrementoperator-precedence

Following snippet doesn't produce expected result


I found this in one of the Java programming quiz question.

public class Calculator {
  public static void main(String[] args) {
    int i = 0;
    Calculator c = new Calculator();
    System.out.print(i++ + c.opearation(i));
    System.out.print(i);
  }
  public int operation(int i) {
    System.out.print(i++);
    return i;
  }
}

Executing above snippet gives me the result of 121. I'm expecting it to be 111. I'll explain how I interpreted it.

+ addition operator would get executed from right to left (ref: operator precedence). So, c.operation(0) is invoked first and it prints the value 1 instead I'm expecting the value to be 0 since System.out.print prints the value of i first and then increments the i value since it is a post increment operator.

Secondly, the i value 1 is returned to the main and the statement System.out.print(i++ + 1) gets executed now. And since i has post increment operator it should have executed like 0 + 1 and produced the result 1 insted it printed result as 2.

Thirdly, the i value is now incremented to 1 and this gets printed as expected.

In short, I'm expecting the value to be printed as 011 but I got the result as 121. I'm not sure where my interpretation goes wrong.


Solution

  • Additive Operators

    The additive operators have the same precedence and are syntactically left-associative (they group left-to-right).


    int i = 0;
    System.out.print(i++ + c.operation(i));
    
    1. evaluate i++, get left operand 0, and increment i to 1.

    2. pass i(1) to c.operation(i), execute System.out.print(i++). Print 1 then return 2(right operand).

    3. i++ + c.operation(i) ---> 0 + 2, print 2.

    4. print 1.