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

前端 未结 14 759
误落风尘
误落风尘 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 21:54

    It is not the same. The left hand side will always be evaluated before the right hand side, and the brackets don't specify an order of execution, but a grouping of commands.

    With:

          x == (x = y)
    

    You are basically doing the same as:

          x == y
    

    And x will have the value of y after the comparison.

    While with:

          (x = y) == x
    

    You are basically doing the same as:

          x == x
    

    After x took y's value. And it will always return true.

提交回复
热议问题