Like char c = (char) -98; works?

I want to know how the next line of code works?

char c = (char) -98; 

To my knowledge, all signed numbers are stored in the form of 2 additions. Thus, -98 will be stored in the form of 2 additions. Therefore, if you type it in char. How is this type casting done by the JVM?

Please correct me if I am wrong.

+6
source share
2 answers

When you write:

 char c = (char) -98; 

This is the same as entry 1 :

char c = 65438;

[Because 65438 = 2^16 - 98 ]

If you explicitly convert int to char first 16 bits will be deleted.


1 -98 in 2 add-ons

11111111111111111111111110011110 .

When casting to char , only 16 bits are saved:

1111111110011110

This value is 65438 ..

Additional Information:

+7
source

From the documentation:

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\ u0000' (or 0) and a maximum value of '\ uffff' (or 65,535 inclusive).

A source

These are just 16-bit unsigned integers.

People reported that if char > 65535 , the result was char % 65536 , so I assume your char c will be -98 % 65536 , which will result in 65536 - 98 = 65438 .

In any case, to be 100% sure, why don't you just give it a try?

UPDATE:

I see that you want to know what the output of System.out.println(char) (for example).

Char and String literals can contain Unicode characters (UTF-16)

A source

So, System.out.println((char)65438) equivalent to System.out.println('\uFF9E') , which, looking at the UTF-16 encoding table ( source ), is a HALFWIDTH KATAKANA VOICED SOUND MARK . It will be printed, but if the font supports this character, one of these fonts is Arial Unicode MS .

+2
source

All Articles