aspose file tools
The moose likes Java in General and the fly likes Addition of characters and integers in Sysout Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Addition of characters and integers in Sysout" Watch "Addition of characters and integers in Sysout" New topic
Author

Addition of characters and integers in Sysout

Soniya Ahuja
Ranch Hand

Joined: Jul 20, 2008
Posts: 83
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!


SCJP 1.5 | SCWCD 5 | SCJP 6.0
[url]http://a2zjava.webs.com[/url] - Online training for Java/JSPs and Servlets/SCJP/SCWCD
http://soniyaahuja.webs.com
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

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.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
Antany Vasanth
Ranch Hand

Joined: Jan 28, 2009
Posts: 43
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

Joined: Jul 20, 2008
Posts: 83
Thanks everyone for the replies. This explains the answers to me now
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Addition of characters and integers in Sysout
 
Similar Threads
Promotions?
Strange behaviour in char expression inside switch
Super class??
Static
about ++