Friday, 8 September 2017

operator keyword - Pre-increment and post-increment behavior in Java





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?


Answer




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


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...