rajeev
rajeev

Reputation: 499

require of casting in Byte and Short

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

Upvotes: 1

Views: 763

Answers (5)

Saj
Saj

Reputation: 18712

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.

Upvotes: 0

arshajii
arshajii

Reputation: 129537

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.

Upvotes: 9

roehrijn
roehrijn

Reputation: 1427

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.

Upvotes: 2

upog
upog

Reputation: 5516

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

Upvotes: 0

Makoto
Makoto

Reputation: 106470

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.

Upvotes: 1

Related Questions