The output of the following code is declared as "6" when I try to execute this.
When I am trying to think through this, the expression "k += 3 + ++k; should have been evaluated as k = k + (3 + ++k); but in this case the output should have been 7. Looks like it was evaluated as k = k + 3 + ++k; which resulted in 6.
Could someone please explain me why the expression was evaluated as "k + 3 + ++k" instead of " k + (3 + ++k); ?
public class TestClass {
public static int m1(int i){
return ++i;
}
public static void main(String[] args) {
int k = m1(args.length);
k += 3 + ++k;
System.out.println(k);
}
}
Take a look at the behaviour in JLS - Compound Assignment Operator. I'll quote the relevant two paragraphs here, just for the sake of completeness of the answer:
Emphasis mine.
So, the left hand operand is evaluated first, and it is done only once. And then, the evaluated value of left hand operand,
1
in your case, is added with the result of right hand operand, which turns out to be5
. Hence the result6
.