Why does this Java code compile?

前端 未结 14 2051
情深已故
情深已故 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:45

    Let's break it down step by step, right associative

    int x = x = 1
    

    x = 1, assign 1 to a variable x

    int x = x, assign what x is to itself, as an int. Since x was previously assigned as 1, it retains 1, albeit in a redundant fashion.

    That compiles fine.

    int x = x + 1
    

    x + 1, add one to a variable x. However, x being undefined this will cause a compile error.

    int x = x + 1, thus this line compile errors as the right portion of the equals will not compile adding one to an unassigned variable

提交回复
热议问题