When we try to assign a variable of large-sized type to a smaller sized type, Java will generate an error, incompatible types: possible lossy conversion, while compiling the code.
When we perform arithmetic operation on primitive types smaller than Integer, Java automatically converts it into Integer. For larger primitives type does not change.
byte A=11; int B, C; //line 1
A = (byte)C / (byte)B; //line 2
In line 2(code mentioned above) right hand side is converted to Integer as division operation is performed on byte values. You can try below mentioned code:
Object obj = (byte)C / (byte)B;
System.out.println(((Object)obj).getClass().getName());
This will print java.lang.Integer
.
To solve it you can cast whole result to byte:
A = (byte) (C / B);