1
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);
4

5 回答 5

9

这是因为第二个片段导致根据JLS §5.1.2扩大原始转换:

原始类型的 19 种特定转换称为扩展原始类型转换:

  • byteshort, int, long, float, 或double

  • shortint, long, float, 或double

  • charint, long, float, 或double

  • intlong, float, 或double

  • longfloatdouble

  • floatdouble

而第一个没有;请注意,没有从inttoshort或的转换byte

于 2013-09-07T16:06:34.080 回答
2

文字“20”由编译器 作为int处理。IntegerLongFloatDouble可以处理大于或等于int范围的数字范围,因此编译器可以进行隐式转换。ShortByte确实有更小的范围,可以防止隐式转换。如果数字不能由ByteShort表示,则显式转换可能会导致ClassCastException

于 2013-09-07T16:11:21.777 回答
1

如果您要这样构造它,则 for 的构造函数需要 a ,对于 的构造函数也是Byte如此。byteShort

没有强制转换或类型文字的数字始终被视为int.

于 2013-09-07T16:06:19.343 回答
0

byte 的构造函数定义为

 public Byte(byte value) {
        this.value = value;
    }

它需要 byte ,因为您传递的整数需要显式转换,简而言之也是如此

于 2013-09-07T16:11:20.377 回答
0
Byte byte1=new Byte((byte) 20);

字节数据类型是一个 8 位有符号二进制补码整数。它的最小值为 -128,最大值为 127(含)。

但是,上面的 20 是一个整数。

int 数据类型是一个 32 位有符号二进制补码整数。它的最小值为 -2,147,483,648,最大值为 2,147,483,647(含)。

因此,字节不能将任何值超出范围。当您尝试分配一个整数时,例如130而不是20 ,您将丢失数据(位),因为130超出了字节范围。通过强制转换,您告诉编译器您知道转换。

于 2013-09-07T16:16:35.230 回答