问题描述:

Byte byte1=new Byte((byte) 20);

Short short1=new Short((short) 20);

why i am bound to use cast operator in Byte and Short but i am not using cast operator in other DataType

Integer integer=new Integer(20);

Long long1=new Long(20);

Double double1=new Double(20);

Float float1=new Float(20);

网友答案:

It's because the second snippet results in widening primitive conversions in accordance with JLS §5.1.2:

19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double

  • short to int, long, float, or double

  • char to int, long, float, or double

  • int to long, float, or double

  • long to float or double

  • float to double

Whereas the first does not; notice that there is no conversion from int to short or byte.

网友答案:

The literal "20" is handled as an int by the compiler. Integer, Long, Float and Double can handle number ranges which are greater or equal than the range of int so the compiler can do an implizit cast. Short and Byte do have smaller ranges which prevents implizit casts. Casting explizitly may result in a ClassCastException if the number is not representable by Byte or Short.

网友答案:

The constructor for Byte requires a byte if you're constructing it like that, and the same is true for the constructor of Short.

Numbers without a cast or a type literal are always seen as int.

网友答案:

The Constructor of byte is defined as

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

It expects byte , since you are passing integer you need to cast explicitly, Same holds true for short

网友答案:
Byte byte1=new Byte((byte) 20);

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

But, 20 above is an integer.

The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

So, byte cannot take any value out of the range. You will lose data (bits) when you try assigning an integer say 130 rather than 20 because 130 is out of byte range. By casting you are telling the compiler that you are aware of the conversion.

相关阅读:
Top