Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does char c = (char) -98; works?

I want to know how does following line of code works?

char c = (char) -98;

As per my knowledge all signed numbers are stored in 2's complement form. So -98 will be stored in 2's complement form. So if you type cast it into char. How does this type casting is done by JVM?

Please correct me if I am wrong.

like image 849
Jigar Avatar asked Dec 09 '13 07:12

Jigar


2 Answers

When you write:

char c = (char) -98;

It's the same like writing1:

char c = 65438;

[Because 65438 = 2^16 - 98]

When explicitly converting an int to char, the first 16 bit will be removed.


1 -98 in 2's complement is

11111111111111111111111110011110.

The casting to char keeps only 16-bits:

1111111110011110

This value represents 65438..

More reading:

  • JLS
  • 2's complement
like image 181
Maroun Avatar answered Oct 12 '22 22:10

Maroun


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).

Source

They are just 16-bit unsigned integers.

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

Anyway to be 100% sure, why don't you just try it?

UPDATE:

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

Literals of types char and String may contain any Unicode (UTF-16) characters

Source

So System.out.println((char)65438) is then equivalent to System.out.println('\uFF9E'), which by doing a lookup on the UTF-16 encoding table (source) is a HALFWIDTH KATAKANA VOICED SOUND MARK. It will only be printed though if the font supports this character, one of such fonts is Arial Unicode MS.

like image 44
skiwi Avatar answered Oct 13 '22 00:10

skiwi