Puzzle of compound assignment operator

Source: Internet
Author: User

Let's look at an example:

// Add a declaration  while I = 0) {      i>>>=1;       }

Add a line of code at the Add Declaration to make the above loop a dead loop

Long i =-1;

or int =-1;

Oh, no!!!

Try short i =-1;

What's up?

Dead cycle!!!!

Since there's been a strange phenomenon (at least it's weird for me)

Why is it?

Lookup data A specification for complex assignment operations

In a compound assignment operation, a type that is less than int is promoted by an int type (that is, widening), then computed, and then narrowed to the specified operation.

That is, when the type of I is short, it is converted to type int (0xFFFFFFFF), then to the right (0x7FFFFFFF), and then to Short (0xFFFFFFFF).

Then watch the following code:

 Short x = 1,short y = 2, Short z = x + y;

Run discovery

Thirtyfirst.java:7: Error: Possible loss of        precision Short z = x + y                    ;  ^  Short   found:    int1 errors

In other words, there is an implicit extension to int, which then needs to be forced to a short type

Summarize:

<1> when arithmetic operations are performed, if the values on both sides of the operator are lower than int (that is, the byte or short type is automatically converted to the int type first)

<2>, at the time of the operation, will be automatically converted to the high level of the one to do the operation, so the result is also a high level of that, if you want to lower the need to force type conversion

Puzzle of compound assignment operator

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.