gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:26:55 25 4
gpt4 key购买 nike

我知道编译 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com