Consider the following code:
System.out.println('G'+2);
The output is 73. Can I know why and how?
In java, a char
occupies 16 bit in UTF-16
encoding.
G
's unicode is U+0047
, in binary 0000 0000 0100 1111
.
When you sum a char
and an int
(32 bit), the char
will be converted to int
by inserting 0
into the begin of its binary representation. So 0000 0000 0100 1111
is converted to 0000 0000 0000 0000 0000 0000 0100 1111
(in decimal, 71).
That's why you get 73
.
In code you are going to add character to int. Value of character 'G' is :71
See this for more details: ascii table