• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Addition of characters and integers in Sysout

 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks everyone for the replies. This explains the answers to me now
 
It was the best of times. It was the worst of times. It was a tiny ad.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic