Frage

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);
}

}

War es hilfreich?

Lösung

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:

Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

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 be 5. Hence the result 6.

Andere Tipps

Official Docs on Operators says

All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

So + is evaluated left-to-right,where as assignment operators are evaluated right to left.

Now you got your answer right ??

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top