While practicing Java I randomly came up with this:
class test
{
public static void main(String arg[])
{
char x='A';
x=x+1;
System.out.println(x);
}
}
I thought it will throw an error because we can't add the numeric value 1
to the letter A
in mathematics, but the following program runs correctly and prints
B
How is that possible?
Because type char effectively works like a 16-bit unsigned int.
So setting
char x='A'
is almost equivalent toint x=65
When you add one; you get 66; or ASCII 'B'.This is the equivalent program of your program:
But as you see,
next=start+1
, will not work. That's the way java handles.The reason could be that we may accidentally use
start
, with integer1
thinking thatstart
is anint
variables and use that expression. Since, java is so strict about minimizing logical errors. They designed it that way I think.But, when you do,
char next='\u0041'+1;
it's clear that'\u0041'
is a character and1
will be implicitly converted into a 2 byte. This no mistake could be done by a programmer. May be that's the reason they have allowed it.char
is 2 bytes in java.char
supportsunicode
characters. When you add or subtract a char var with an offset integer, the equivalentunicode
character in the unicode table will result. Since,B
is next toA
, you gotB
.char
are stored as 2 byte unicode values in Java. So ifchar x = 'A'
, it means thatA
is stored in the unicode format. And in unicode format, every character is represented as an integer. So when you sayx= x+1
, it actually increments the unicode value of theA
, which printsB
.A
char
is in fact mapped to anint
, look at the Ascii Table.For example: a capital A corresponds to the decimal number 65. When you are adding 1 to that
char
, you basicly increment the decimal number by 1. So the number becomes 66, which corresponds to the capital B.A
char
in Java is just an integer number, so it's ok to increment/decrement it. Each char number has a corresponding value, an interpretation of it as a character, by virtue of a conversion table: be it the ASCII encoding, or the UTF-8 encoding, etc.Come to think of it, every data in a computer - images, music, programs, etc. are just numbers. A simple character is no exception, it's encoded or codified as a number, too.
you have to type cast the result after adding using parenthesis like this:
else you will get loose of data error.