Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Byte can't hold a value that is within its range?

You can't put a large value in small cup. Well, OK, you can, but you'll lose some. You'll get, as we say, spillage. the compiler tries to help prevent this if it can tell from your code that something's not going to fit in container(variable) you are using.

For Example,

int x= 24;

byte b= x;

// Won't work!!

now range of byte is -128 to 127. Now, my question is why doesn't this work? After all, the value of x is 24, and 24 is definitely small enough to fit into byte (may be a very novice level question, but i am really confused about this concept).


1 Answers

You know that byte b= x; is equivalent to byte b= 24;, and an intelligent compiler can also tell that, but Java is specified in a very precise way to ensure that all compilers do the same thing, and it does not allow compilers to notice this equivalence for purposes of accepting or rejecting the program. (They can use it for performing optimization afterward, though.) All the compiler is supposed to know is that the expression x has the static type int, so it can't guarantee that byte b= x is assigning a value in the range of byte.

Instead, you have to write byte b = (byte) x, explicitly converting ("casting") the expression x to type byte.

(This is a general principle with static typing — with any type system, there will always be some otherwise-correct programs that the type system rejects. In this case, the type system doesn't let you assign from int to byte without a cast.)

like image 120
ruakh Avatar answered Feb 05 '26 08:02

ruakh