Tuesday, August 28, 2018

How are java increment statements evaluated in complex expressions



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?


Answer



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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...