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