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