Java Multiple transformation issues

Source: Internet
Author: User

Let's look at a simple question, what does the following code print?

 Public class Hello {    publicstaticvoid  main (string[] args) {        System.out.println ( (int) (char) (byte)-1);}    }

I believe many people will say that the final output is-1, but the actual result is 65535, which is why?

This program involves three types of conversions, which closely depend on the symbolic expansion behavior of the transformation. Java uses a 2-based complement of binary operations, so the int type of-1 with 32-bit complement means 11111 ... 1111. The transformation from int to byte is very simple, it performs a narrowing of the basic type conversion , directly cut the 8-bit more than the part, leaving 11111111, still represents-1.

The transition from byte to char is slightly cumbersome because byte is a signed type and char is an unsigned type (representing a character 16 bits). Converting an integer type to a wider integer type is usually lossless (such as int to long), but it is not possible to represent a negative byte value with a single character. Therefore, it is generally assumed that the conversion from byte to char is not a widening of the basic type conversions , but rather widens and narrows the basic type conversions : Byte is first converted to int, and then int is converted to char.

These seem more complex, with a rule describing the symbolic expansion behavior when converting from a narrower integer type to a wider one: if the initial numeric type is signed, the symbol expands , and if it is char, it performs 0 expansion Regardless of the type to be converted. Using this rule to see the conversion from byte to Char, Byte is a signed type, so the symbol expands, 11111111 expands to 1111111111111111, Convert to 10 binary number is 65535. Widening from char to int is also a simple widening of the basic type conversion. So the final output is 65535.

Java Multiple transformation issues

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.