Why does this Java code compile?

前端 未结 14 2166
情深已故
情深已故 2021-01-30 01:24

In method or class scope, the line below compiles (with warning):

int x = x = 1;

In class scope, where variables get their default valu

14条回答
  •  长发绾君心
    2021-01-30 02:00

    In java or in any modern language, assignment comes from the right.

    Suppose if you are having two variables x and y,

    int z = x = y = 5;
    

    This statement is valid and this is how the compiler splits them.

    y = 5;
    x = y;
    z = x; // which will be 5
    

    But in your case

    int x = x + 1;
    

    The compiler gave an exception because, it splits like this.

    x = 1; // oops, it isn't declared because assignment comes from the right.
    

提交回复
热议问题