int k = 1; int i = +k + k++ On running, the value of i is 2. ((+k) + (k++)) ( 1 + 1 ) I can understand this assuming that unary + and postfix operators have the same precedence. But, according to JLS the postfix operator has higher precedence compared to unary +, so that k++ should be evaluated first and then +k. ((+k) + (k++)) ( 2 + 1 ) According to this, answer is 3. Please explain, why the compiler is not following the precedence given in the JLS.
I was evaluating expressions the same way, and when writing code I'd always use parens like any sane person. But the compiler doesn't evaluate expressions that way. You have the right technique with replacing all the variables with values as a first step. But the rule you have to follow is this: Evaulate left to right, and respect predecence. Try this: i = k++ + k; Now you get 3. 1 (2) + 2 = 3