Reputation: 5959
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;//compilation error
}
}
Why 20
is automatically type-casted to byte
while x
not?
Upvotes: 0
Views: 1411
Reputation: 17923
Up-casting is automatic where as down-casting or narrowing (byte c=x;
) should be explicit as it might cause loss of precision which a programmer should be aware of explicitly. To correct it you need to put an explicit cast byte c=(byte)x;
Upvotes: 0
Reputation: 1135
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
Upvotes: 3
Reputation: 9821
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.
Upvotes: 1
Reputation: 30465
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)."
Upvotes: 1
Reputation: 66657
X defined as integer, while narrowing there may be data loss, that is why compiler error. Refer jvm spec for conversions & promotions
Upvotes: 0
Reputation: 2477
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.
Upvotes: 1
Reputation: 204894
Because x
is an int
and has a wider range as byte
. That is why there may be data loss is you assign it to byte
.
20
is a constant and while compile time garanteed to be in the range of byte
.
Upvotes: 5