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

前端 未结 14 985
误落风尘
误落风尘 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:44

    As LouisWasserman said, the expression is evaluated left to right. And java doesn't care what "evaluate" actually does, it only cares about generating a (non volatile, final) value to work with.

    //the example values
    x = 1;
    y = 3;
    

    So to calculate the first output of System.out.println(), the following is done:

    x == (x = y)
    1 == (x = y)
    1 == (x = 3) //assign 3 to x, returns 3
    1 == 3
    false
    

    and to calculate the second:

    (x = y) == x
    (x = 3) == x //assign 3 to x, returns 3
    3 == x
    3 == 3
    true
    

    Note that the second value will always evaluate to true, regardless of the initial values of x and y, because you are effectively comparing the assignment of a value to the variable it is assigned to, and a = b and b will, evaluated in that order, always be the same by definition.

提交回复
热议问题