Pre-increment and post-increment behavior in Java [duplicate]

a 夏天 提交于 2020-01-25 04:22:05

问题


Can someone explain the implementation of the following code:

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

I'm expecting the output to be 3 as explained below: Since '/' has higher precedence than '+' it is evaluated first.

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)

So the result of the '/' operation within parantheses is 2 / 2 = 1. Then comes the '+' operation:

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)

So, the result should be 3 + 1 = 4. But when I evaluate this expression, I'm getting 2. How come this happen?


回答1:


Since '/' has higher precedence than '+' it is evaluated first.

No, expressions are evaluated left to right - each operand is then associated using precedence rules.

So your code is equivalent to:

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


来源:https://stackoverflow.com/questions/28829957/pre-increment-and-post-increment-behavior-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!