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

前端 未结 14 756
误落风尘
误落风尘 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.

提交回复
热议问题