How are java increment statements evaluated in complex expressions

久未见 提交于 2019-11-27 04:52:36

问题


What is the output of the following code:

int x = 2;  
x += x++ * x++ * x++;  
System.out.println(x);  

I understand that ++variableName is pre-increment operator and the value of variableName is incremented before it is used in the expression whereas variableName++ increments its value after the expression is executed. What I want to know is - how does this logic apply here?


回答1:


Its easier to see the what is going on with x = 1 instead of 2. The output for x=1 is 7.

The key to the understanding of this is in JLS 15.7.2 which states that the every operand is fully evaluated before any part of the operation is performed.

The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

Thus, x++ (each of 3 times, left to right with appropriate precedence which isn't an issue here) is evaluated, then the operation * is evaluated and assigned to the original value.

x = 1 + (1 * 2 * 3)

If x starts out with 2, you get:

x = 2 + (2 * 3 * 4)

Unlike in C, this is well defined in Java and will behave the same on each invocation in any runtime.

Associated ideone if anyone wants to run it for themselves: https://ideone.com/Y2qcJ6



来源:https://stackoverflow.com/questions/23308228/how-are-java-increment-statements-evaluated-in-complex-expressions

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