Operation operations in Java involving Byte, short, and char types

Source: Internet
Author: User
Tags return
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.




Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.