According to the Java standard the short
and char
types both use 2 bytes so when I code something like:
char ch = 'c';
short s = ch;
There is an error saying "possible loss of precision". What am I missing here?
char is unsigned, short is signed. So while they are both 2-byte long, they use the sixteenth bit for different purposes. The range of the char type is 0 to 2^16 - 1 (0 to 65535). The short range is -2^15 to 2^15 - 1 (−32,768 to 32,767).
Yes, char is just like any other primitive type, you can just compare them by == .
Char has a minimum value of 0 and a maximum value of 65,535. Short has a minimum value of -32,768 and a maximum value of 32,767. Integer has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647. So char can fit into integer but not into short.
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).
char
is unsigned, short
is signed.
So while they are both 2-byte long, they use the sixteenth bit for different purposes.
The range of the char
type is 0 to 2^16 - 1 (0 to 65535).
The short
range is -2^15 to 2^15 - 1 (−32,768 to 32,767).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With