I\'d a code snippet:
class AutoTypeCast{
public static void main(String...args){
int x=10;
byte b=20;//no compilation error
byte c=x;
In this case x
is initialized to 10, so there will be no data loss in the conversion from a 32-bit int
to an 8-bit byte
. But in general, when converting from int
to byte
, there can be data loss, so the rules of the Java language forbid assigning int
values to a byte
without a cast. This rule is designed to make it more difficult to write buggy code. By inserting the (byte)
cast, you are effectively telling the compiler: "Yes, I have thought about the possibility of data loss, and it is not a problem here (or, that's actually what I want)."
When the compiler looks at the line
byte b=20;
it knows it's looking for a byte after b=. When it finds a constant numeric value it knows at compile time that it will definitely be in the range of byte so it will automatically cast it.
When is sees the line
byte c=x;
it's once again looking for a byte after c= but instead of finding a numeric constant, finds a variable that already has a defined type and, at compile time, can't be sure that it will be in the range of byte so you get an error.
X defined as integer, while narrowing there may be data loss, that is why compiler error. Refer jvm spec for conversions & promotions
20 always can be represented by a byte, while x, which according to the compiler can be any integer, may be too large to be represented by a byte.
20
is in -128..127
range, so it's value fits into byte
.
Because compiler is not able to figure out the value of X at compile time. So it assume that X can contain value which is greater than byte range. If you make variable X as final then it will not give you compile time error.
final int x=10;
byte b=20;//no compilation error
byte c=x;//no compilation error