简体   繁体   中英

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?

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?

The difference is in the literal itself. You can do:

int z = (int) 2147483648L;

because now you've got a "long" literal. So basically, there are two steps involved:

  • Parsing the literal to a valid value for that literal type ( int in your earlier examples, long for the "big" one)
  • Converting that value to the target type

The error is because by default all numeric integer literals are int and 2147483648 is out of range.

To code this, you need to make it a long with an explicit downcast to int :

    int z = (int)2147483648L; // compiles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM