Operations in Java, which involve byte, short, and char types, first convert the values to the int type, then the int type value, and finally the result of the type int. So, if you add two byte values, you end up with the result of an int type. If you need to get a byte type result, you must explicitly convert the result of this int type to the byte type. For example, the following code will cause the compilation to fail:
Class Badarithmetic {
static byte Addoneandone () {
byte a = 1;
byte B = 1;
byte C = (A + b);
return C;
}
}
When the above code is encountered, Javac gives the following hints:
Type.java:6: Possible loss of precision
Found:int
Required:byte
byte C = (A + b);
^
1 Error
In order to remedy this situation, you must explicitly convert the result of type A + B to the byte type. The code is as follows:
Class Goodarithmetic {
static byte Addoneandone () {
byte a = 1;
byte B = 1;
byte C = (byte) (A + B);
return C;
}
}
The operation can be compiled by Javac and produce goodarithmetic.class files.