Question

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

Was it helpful?

Solution

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

OTHER TIPS

You need to typecase your int into a byte this way:

byte b = (byte) x;

Else the compiler will give you an error at compilation
Keep in mind typecasting comes with loss of data if the value is outside the boundaries for the primitive datatype you are storing in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top