While practicing Java I randomly came up with this:
class test
{
public static void main(String arg[])
{
char x=\'A\';
x=x+1;
you have to type cast the result after adding using parenthesis like this:
x='A';
x = (char) (x+1);
else you will get loose of data error.
char
is a numeric type (2 bytes long), and is also the only unsigned numeric primitive type in Java.
You can also do:
int foo = 'A';
What is special here is that you initialize the char
with a character constant instead of a number. What is also special about it is its string representation, as you could witness. You can use Character.digit(c, 10)
to get its numeric value (as an int
, since 2 ^ 16 - 1 is not representable by a short
!).
char
are stored as 2 byte unicode values in Java. So if char x = 'A'
, it means that A
is stored in the unicode format. And in unicode format, every character is represented as an integer. So when you say x= x+1
, it actually increments the unicode value of the A
, which prints B
.
Because type char effectively works like a 16-bit unsigned int.
So setting char x='A'
is almost equivalent to int x=65
When you add one; you get 66; or ASCII 'B'.