java - 自动装箱:为什么 Short S1 = 100;编译正常,但 Long F1 = 100;失败的?

标签 java autoboxing

我知道编译 Long F1 = 100; 会失败,因为 100 是一个整数,所以编译器会将其装箱为 Integer,并且包装器类型无法扩展.

但是为什么编译 Short S1 = 100; 会成功呢?非常感谢您的帮助。

最佳答案

来自 SCJP: 的第 3 章

The following is legal,

byte b = 27;

but only because the compiler automatically narrows the literal value to a byte. In other words, the compiler puts in the cast. The preceding code is identical to the following:

byte b = (byte) 27; // Explicitly cast the int literal to a byte

It looks as though the compiler gives you a break, and lets you take a shortcut with assignments to integer variables smaller than an int. (Everything we're saying about byte applies equally to char and short, both of which are smaller than an int)

在您的情况下,编译器正在使用:

Short s = (short)100;

关于java - 自动装箱:为什么 Short S1 = 100;编译正常,但 Long F1 = 100;失败的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20025718/

相关文章:

linux 上的 java unicode 转换不适用于 mac os x

java - 关于 AsyncTask 中 Java 泛型的问题

java - 使用自动装箱时 JSP 编译错误

Java 整数与字符串自动装箱设计

java - 为什么 Integer 类不需要创建实例?

java - 如何从.java代码创建安装安装程序?

java - Thread.sleep() 是否不让其他线程运行?

java - JLabel 更改时 Applet 重新定位

kotlin - 为什么 Kotlin '===' 引用相等运算符对相同的对象引用返回 false?

java - 使用PreparedStatement::setInt null 输入会发生什么