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

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

    == is a comparison equality operator and it works from left to right.

    x == (x = y);
    

    here the old assigned value of x is compared with new assign value of x, (1==3)//false

    (x = y) == x;
    

    Whereas, here new assign value of x is compared with the new holding value of x assigned to it just before comparison, (3==3)//true

    Now consider this

        System.out.println((8 + (5 * 6)) * 9);
        System.out.println(8 + (5 * 6) * 9);
        System.out.println((8 + 5) * 6 * 9);
        System.out.println((8 + (5) * 6) * 9);
        System.out.println(8 + 5 * 6 * 9);
    

    Output:

    342

    278

    702

    342

    278

    Thus, Parentheses plays its major role in arithmetic expressions only not in comparison expressions.

提交回复
热议问题