Why does Java require an explicit cast on a final variable if it was copied from an array?

前端 未结 4 662
长发绾君心
长发绾君心 2021-01-01 08:28

Starting with the following code...

byte foo = 1;
byte fooFoo = foo + foo;

When I try compiling this code I will get the following error...

4条回答
  •  暖寄归人
    2021-01-01 09:08

    It is indeed what compiler do in constant folding when used with final, as we can see from byte code:

        byte f = 1;
        // because compiler still use variable 'f', so `f + f` will 
        // be promoted to int, so we need cast
        byte ff = (byte) (f + f);
        final byte s = 3;
        // here compiler will directly compute the result and it know
        // 3 + 3 = 6 is a byte, so no need cast
        byte ss = s + s;
        //----------------------
        L0
        LINENUMBER 12 L0
        ICONST_1 // set variable to 1
        ISTORE 1 // store variable 'f'
        L1
        LINENUMBER 13 L1
        ILOAD 1 // use variable 'f'
        ILOAD 1
        IADD
        I2B        
        ISTORE 2 // store 'ff'
        L2
    
        LINENUMBER 14 L2
        ICONST_3 // set variable to 3
        ISTORE 3 // store 's'
        L3
        LINENUMBER 15 L3
        BIPUSH 6 // compiler just compute the result '6' and set directly
        ISTORE 4 // store 'ss'
    

    And if you change your final byte to 127, it will also complain:

        final byte s = 127;
        byte ss = s + s;
    

    in which cases, the compiler compute the result and know it out of limit, so it will still complain they are incompatible.

    More:

    And here is another question about constant folding with string:

提交回复
热议问题