Why during autoboxing final long to Byte compilation error happens, but final int to Byte is ok?

南笙酒味 提交于 2019-12-23 07:27:44

问题


There is no error during auto-boxing of constants with int and short types to Byte, but constant with long type do has error. Why?

final int i = 3;
Byte b = i; // no error

final short s = 3;
Byte b = s; // no error


final long l = 3;
Byte b = l; // error

回答1:


From JLS Sec 5.2, "Assignment contexts" (emphasis mine):

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
  • A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:

    • Byte and the value of the constant expression is representable in the type byte.
    • ...

It's simply not allowed for longs by the spec.

Note that the second bullet point here says that this happens irrespective of the boxing: assigning a constant long expression to a byte variable would similarly fail:

// Both compiler errors.
byte primitive = 0L;
Byte wrapped = 0L;


来源:https://stackoverflow.com/questions/46206288/why-during-autoboxing-final-long-to-byte-compilation-error-happens-but-final-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!