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

前端 未结 4 660
长发绾君心
长发绾君心 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:05

    The value 1 fits nicely into a byte; so does 1+1; and when the variable is final, the compiler can do constant folding. (in other words: the compiler doesn't use foo when doing that + operation; but the "raw" 1 values)

    But when the variable is not final, then all the interesting rules about conversions and promotions kick in (see here; you want to read section 5.12 about widening primitive conversions).

    For the second part: making an array final still allows you to change any of its fields; so again; no constant folding possible; so that "widening" operation is kicking in again.

提交回复
热议问题