Purpose of char in java
I'm seeing both char and short are two bytes each, also the following is valid:
char a = 'x';
int b = a;
long c = a;
However when I do short d = a; I'm getting an error that cannot convert from char to short. even though both are two bytes.
One use of char I can see is when you print it, it displays the character. Is that the o开发者_Go百科nly use of char?
In Java the data type char
is an unsigned 2 byte variable while a short
is signed 2 byte variable. Because of this difference you cannot convert a char
to a short
because a char
has that extra bit that isn't the signed bit.
This means that if you convert char
to a short
you would have to truncate the char
which would cause the complaining.
You should probably want to read about data types and type casting to have a clear understanding.
When you tried to do short d=a;
you are trying to do the 'Narrowing Primitive Conversion'.
5.1.3 Narrowing Primitive Conversions
The following 22 specific conversions on primitive types are called the narrowing primitive conversions:
short to byte or char char to byte or short int to byte, short, or char long to byte, short, char, or int float to byte, short, char, int, or long double to byte, short, char, int, long, or float
Narrowing conversions may lose information about the overall magnitude of a numeric value and may also lose precision.
While it is true that char is an unsigned 16-bit type, it is not designed to be used as such. Conceptually, char is a Unicode character (more precisely, a character from the Unicode subset that can be represented with 16 bits in UTF-16) which is something more abstract than just a number. You should only ever use chars for text characters. I think that making it an integer type is a kind of bad design on Java's side. It shouldn't have allowed any conversions between char and integer types except by using special utility methods. Like boolean is impossible to convert to integers and back.
char is generally only used for text, yes.
char is unsigned, while short is signed.
check out the Java Docs
it's all there... Char and Short aren't the same.
Normally, I use char for text, and short for numbers. (If I use short. I'd rather use int/long when they're available).
You may want to "cast" the variable. It's done like this:
char a = 'x';
short sVar = (short)a;
System.out.println(a);
System.out.println(sVar);
char
is a Unicode-character and, therefore, must be unsigned. short
is like all other numeric primitive types signed. Therefore, short
and char
cover two different ranges of values causing the compiler to complain about the assignment.
精彩评论