• Post Reply Bookmark Topic Watch Topic
  • New Topic

Addition of characters and integers in Sysout  RSS feed

 
Soniya Ahuja
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I can't understand why 111/112/114 or any such number is being printed for the following line of code
System.out.println(12+'c');

If I print this
System.out.println(Character.getNumericValue('c'));
The output remains constant but I can't understand what happens in the former print statement. I was expecting compile time error or exception, but I get a perfectly working piece of code.

Please explain!
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A char is actually nothing more than a numeric value that is treated differently when printed. For instance, 'A' is 65. As such, 12 + 'A' would be 77, and that would be printed.
 
Antany Vasanth
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Sonia,

Here ASCII value of c = '99' whenever (12+'c') is considered as arithmetic addition operation. Hence the ASCII value of 'c'(99) is added with 12 which results 111.

Its very similar like if you assign int a = 'c'; then a value become 99. if you try to print a, 99 will be printed.

In the above, char is implicitly casted into int. Hence compilation error wont occur.

Here Character.getNumericValue('c') method returns the int value that the specified Unicode character represents.

Regards,
Antany
 
Soniya Ahuja
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone for the replies. This explains the answers to me now
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!