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