Byte byte1=new Byte((byte) 20);
Short short1=new Short((short) 20);
为什么我必须在 Byte 和 Short 中使用强制转换运算符,但我没有在其他 DataType 中使用强制转换运算符
Integer integer=new Integer(20);
Long long1=new Long(20);
Double double1=new Double(20);
Float float1=new Float(20);
这是因为第二个片段导致根据JLS §5.1.2扩大原始转换:
原始类型的 19 种特定转换称为扩展原始类型转换:
byte
到short
,int
,long
,float
, 或double
short
到int
,long
,float
, 或double
char
到int
,long
,float
, 或double
int
到long
,float
, 或double
long
到float
或double
float
至double
而第一个没有;请注意,没有从int
toshort
或的转换byte
。
文字“20”由编译器 作为int处理。Integer、Long、Float和Double可以处理大于或等于int范围的数字范围,因此编译器可以进行隐式转换。Short和Byte确实有更小的范围,可以防止隐式转换。如果数字不能由Byte或Short表示,则显式转换可能会导致ClassCastException。
byte 的构造函数定义为
public Byte(byte value) {
this.value = value;
}
它需要 byte ,因为您传递的整数需要显式转换,简而言之也是如此
Byte byte1=new Byte((byte) 20);
字节数据类型是一个 8 位有符号二进制补码整数。它的最小值为 -128,最大值为 127(含)。
但是,上面的 20 是一个整数。
int 数据类型是一个 32 位有符号二进制补码整数。它的最小值为 -2,147,483,648,最大值为 2,147,483,647(含)。
因此,字节不能将任何值超出范围。当您尝试分配一个整数时,例如130而不是20 ,您将丢失数据(位),因为130超出了字节范围。通过强制转换,您告诉编译器您知道转换。