Reputation: 499
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
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
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
toshort
,int
,long
,float
, ordouble
short
toint
,long
,float
, ordouble
char
toint
,long
,float
, ordouble
int
tolong
,float
, ordouble
long
tofloat
ordouble
float
todouble
Whereas the first does not; notice that there is no conversion from int
to short
or byte
.
Upvotes: 9
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
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