1

Consider the following code:

System.out.println('G'+2);

The output is 73. Can I know why and how?

xingbin
  • 27,410
  • 9
  • 53
  • 103
Mados
  • 53
  • 8

3 Answers3

3

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.

xingbin
  • 27,410
  • 9
  • 53
  • 103
0

It takes ascii value of G and adds 2 to it.

0

In code you are going to add character to int. Value of character 'G' is :71

See this for more details: ascii table

MinA
  • 405
  • 4
  • 9