While developing a web application in JSF, I came across an expression which was evaluated in a way that I couldn’t follow. Let’s represent the same expression with a simple Java code.
final public class Main
{
public static void main(String[] args)
{
int x=5;
int temp=10;
temp=temp + 1 + x;
System.out.println("temp = "+temp);
int var=10;
var=var++ + x;
System.out.println("var = "+var);
}
}
In the above simple code snippet, the first case is obvious and it displays the value 16 through the statement System.out.println("temp = "+temp);. There is no question at all about it but in the second case, I have represented the same thing using the shorthand operator ++ (var++) and that causes the value 15 to be displayed on the console instead of displaying 16. How is this expression evaluated here?
Here, there is an obvious thing that should be mentioned. In the expression var++, 10 is first passed and that value (not 11) is used to evaluate the entire expression on the right of the assignment which is in this case var++ + x and then var is incremented by 1. Accordingly, the assignment to itself (var) can not be observed here.
Where was the incrementation lost?
Post increment operator like x++ means first you use the value x then you increment and in our case
assignment takes precedence.
Try this
and you should get the value of 16.