预增量和增量后行为在Java中[复制](Pre-increment and post-increme

2019-10-22 03:32发布

这个问题已经在这里有一个答案:

  • 有没有在Java X ++和++ X之间的差异? 16个回答
  • 前及在C,C ++,Java的后递增操作人员的行为,&C#[复制] 6个回答

有人可以解释下面的代码执行:

int j = 1;
System.out.println(j-- + (++j / j++));

我期待的输出为3如下面所解释:由于“/”具有比“+”它首先计算更高的优先级。

op1 = ++j (Since it is pre-increment, the value is 2, and j is 2)
op2 = j++ (Since it is post-increment, 2 is assigned and j is incremented to 3)

所以括号内的“/”操作的结果为2/2 = 1。然后是“+”操作:

op1 = j-- (Since it is Post-increment, the value is 3, and j is decremented to 2)
op2 = 1 (The result of the '/' was 1)

所以,结果应该是3 + 1 = 4。但是,当我评价这种表情,我越来越2.为什么出现这种情况?

Answer 1:

由于“/”具有比“+”它首先计算更高的优先级。

不,表达式是从左向右计算的 - 那么每个操作数是利用优先规则有关。

所以,你的代码就相当于:

int temp1 = j--; //1
int temp2 = ++j; //1
int temp3 = j++; //1
int result = temp1 + (temp2 / temp3); //2


文章来源: Pre-increment and post-increment behavior in Java [duplicate]