Compound assignment operator for Java

Source: Internet
Author: User
1. Introduction of the problem

Cut to the chase, look at the following code, the results should be how

public class app{public    static void Main (string[] args) {        byte a=1;    int B = Ten;     A= a+b;         System.out.println (a);         a+=b;    System.out.println (a);    }}

What is the execution result of this code?

2. Implementation results

。。。。。。。。。。。。。。。。。。。 The answer is as follows .....

The compilation of the above code will be error, compile failed. Because in the third row inside the function, the left a is a byte type, the right of a is a byte type B is an int, and when a and B are added, type promotion occurs. The result of the a+b is an int, which naturally causes an error when assigning a value of type int to a byte type. But A+=b, this line of code can be executed normally, this is why?

3. Results analysis

The reason for the error on the third line has already been said, but A+=b, what is the reason for normal execution? according to the JLS (Java language Specification), the compound assignment operator expression E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)) where T is the type of E1, but E1 is only evaluated once. that is to say, the above a+b execution process is this, a = (byte) (a+b), at the time of the assignment of the cast, so it can be compiled through the normal. This explains the results of the compilation above.

Compound assignment operator for Java

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.