Why does this Java code compile?

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

    int x = x = 1; is not equal to:

    int x;
    x = 1;
    x = x;
    

    javap helps us again, these are JVM instruction generated for this code:

    0: iconst_1    //load constant to stack
    1: dup         //duplicate it
    2: istore_1    //set x to constant
    3: istore_1    //set x to constant
    

    more like:

    int x = 1;
    x = 1;
    

    Here is no reason to throw undefined reference error. There is now usage of variable prior to it's initialization, so this code fully comply with specification. In fact there is no usage of variable at all, just assignments. And JIT compiler will go even further, it will eliminate such constructions. Saying honestly, I don't understand how this code is connected to JLS's specification of variable initialization and usage. No usage no problems. ;)

    Please correct if I'am wrong. I cant figure out why other answers, which refer to many JLS paragraphs collect so many pluses. These paragraphs has nothing in common with this case. Just two serial assignments and no more.

    If we write:

    int b, c, d, e, f;
    int a = b = c = d = e = f = 5;
    

    is equal to:

    f = 5
    e = 5
    d = 5
    c = 5
    b = 5
    a = 5
    

    Right most expression is just assigned to variables one by one, without any recursion. We can mess variables any way we like :

    a = b = c = f = e = d = a = a = a = a = a = e = f = 5;
    

提交回复
热议问题