java - Why Byte can't hold a value that is within its range? -
you can't put large value in small cup. well, ok, can, you'll lose some. you'll get, say, spillage. compiler tries prevent if can tell code something's not going fit in container(variable) using.
for example,
int x= 24; byte b= x; // won't work!!
now range of byte -128
127
. now, question why doesn't work? after all, value of x
24
, , 24
small enough fit byte (may novice level question, confused concept).
you know byte b= x;
equivalent byte b= 24;
, , intelligent compiler can tell that, java specified in precise way ensure compilers same thing, , not allow compilers notice equivalence purposes of accepting or rejecting program. (they can use performing optimization afterward, though.) compiler supposed know expression x
has static type int
, can't guarantee byte b= x
assigning value in range of byte
.
instead, have write byte b = (byte) x
, explicitly converting ("casting") expression x
type byte
.
(this general principle static typing — type system, there otherwise-correct programs type system rejects. in case, type system doesn't let assign int
byte
without cast.)
Comments
Post a Comment