Why is x == (x = y) not the same as (x = y) == x?

前端 未结 14 753
误落风尘
误落风尘 2021-01-29 21:11

Consider the following example:

class Quirky {
    public static void main(String[] args) {
        int x = 1;
        int y = 3;

        System.out.println(x =         


        
相关标签:
14条回答
  • 2021-01-29 22:04

    It is related to operator precedence and how operators are getting evaluated.

    Parentheses '()' has higher precedence and has associativity left to right. Equality '==' come next in this question and has associativity left to right. Assignment '=' come last and has associativity right to left.

    System use stack to evaluate expression. Expression gets evaluated left to right.

    Now comes to original question:

    int x = 1;
    int y = 3;
    System.out.println(x == (x = y)); // false
    

    First x(1) will be pushed to stack. then inner (x = y) will be evaluated and pushed to stack with value x(3). Now x(1) will be compared against x(3) so result is false.

    x = 1; // reset
    System.out.println((x = y) == x); // true
    

    Here, (x = y) will be evaluated, now x value become 3 and x(3) will be pushed to stack. Now x(3) with changed value after equality will be pushed to stack. Now expression will be evaluated and both will be same so result is true.

    0 讨论(0)
  • 2021-01-29 22:04

    Consider this other, maybe simpler example:

    int x = 1;
    System.out.println(x == ++x); // false
    x = 1; // reset
    System.out.println(++x == x); // true
    

    Here, the pre-increment operator in ++x must be applied before the comparison is made — just like (x = y) in your example must be calculated before the comparison.

    However, expression evaluation still happens left → to → right, so the first comparison is actually 1 == 2 while the second is 2 == 2.
    The same thing happens in your example.

    0 讨论(0)
提交回复
热议问题