In Java, operations involving the byte, short, and char types will first convert these values to the int type, then perform operations on the int type values, and finally obtain the int type result. Therefore, if two bytes are added, an int value is obtained. To obtain the byte type result, you must explicitly convert the result of this int type to the byte type. For example, the following code may cause compilation failure:
Class BadArithmetic {
Static byte addOneAndOne (){
Byte a = 1;
Byte B = 1;
Byte c = (a + B );
Return c;
}
}
When you encounter the above code, javac will give the following prompt:
Type. java: 6: possible loss of precision
Found: int
Required: byte
Byte c = (a + B );
^
1 error
To remedy this situation, the int type result obtained by a + B must be explicitly converted 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;
}
}
This operation can be compiled through javac and generate the GoodArithmetic. class file.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.