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

java, primitive-types

Solution

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

Problem

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.

Original source