以下代码段未产生预期结果

Following snippet doesn't produce expected result

我在 Java 编程测验问题之一中找到了这个。

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;
  }
}

执行上面的代码片段会得到 121 的结果。我希望它是 111。我将解释我是如何解释它的。

+ 加法运算符将从右到左执行(参考:operator precedence)。因此,首先调用 c.operation(0) 并打印值 1 而不是我期望值是 0 因为 System.out.print 首先打印 i 的值然后增加 i 值,因为它是一个 post 增量运算符。

其次,i 值 1 返回给 main 并且现在执行语句 System.out.print(i++ + 1)。由于 i 有 post 增量运算符,它应该像 0 + 1 一样执行并产生结果 1 insted 它打印结果为 2.

第三,i 值现在增加到 1 并按预期打印。

简而言之,我希望打印的值是 011,但我得到的结果是 121。我不确定我的解释哪里错了。

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. 计算i++,获取左操作数0,并将i增加到1

  2. i(1)传给c.operation(i),执行System.out.print(i++)打印1然后return2(右操作数)。

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

  4. 打印1.