Why does this Java code compile?

前端 未结 14 2045
情深已故
情深已故 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 01:57

    It's roughly equivalent to:

    int x;
    x = 1;
    x = 1;
    

    Firstly, int = ; is always equivalent to

    int ;
     = ;
    

    In this case, your expression is x = 1, which is also a statement. x = 1 is a valid statement, since the var x has already been declared. It is also an expression with the value 1, which is then assigned to x again.

提交回复
热议问题