Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

short and char type in Java [duplicate]

Tags:

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?

like image 956
shreyasva Avatar asked Feb 20 '11 18:02

shreyasva


People also ask

What is the difference between short and char in Java?

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

Can you use == for char in Java?

Yes, char is just like any other primitive type, you can just compare them by == .

Can we type cast char to short?

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.

What is a char type in Java?

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


1 Answers

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

like image 89
Peter Knego Avatar answered Oct 14 '22 16:10

Peter Knego