byte and short data types in Java can accept the value outside the range by explicit cast. The higher data types however can not. Why?
Posted
by
Lion
on Stack Overflow
See other posts from Stack Overflow
or by Lion
Published on 2011-11-18T09:43:28Z
Indexed on
2011/11/18
9:50 UTC
Read the original article
Hit count: 148
java
Let's consider the following expressions in Java.
byte a = 32;
byte b = (byte) 250;
int i = a + b;
This is valid in Java even though the expression byte b = (byte) 250;
is forced to assign the value 250 to b
which is outside the range of the type byte. Therefore, b is assigned -6 and consequently i
is assigned the value 26 through the statement int i = a + b;
.
The same thing is possible with short as follows.
short s1=(short) 567889999;
Although the specified value is outside the range of short, this statement is legal.
The same thing is however wrong with higher data types such int, double, folat etc and hence, the following case is invalid and causes a compile-time error.
int z=2147483648;
This is illegal, since the range of int in Java is from -2,147,483,648 to 2147483647 which the above statement exceeds and issues a compile-time error. Why is such not wrong with byte and short data types in Java?
© Stack Overflow or respective owner