• Post Reply Bookmark Topic Watch Topic
  • New Topic

char Issue  RSS feed

 
Dana Ucaed
Ranch Hand
Posts: 406
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers,

I don't understand why:

returns 1 and

returns 98.

Ascii code for '1' is 49.

Why in first case the result is not 49?

Can someone say where in JLS is specified this behavior?


Thanks a lot!


 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Basically, the println() method is overloaded. There is one for char, and there is one for int (there are also many others). And when you add two chars, it doesn't concatenate. It gets promoted to int, with the ASCII value(s).

So, the first case is calling one method, and the second case is calling a different method.

Henry
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37469
539
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dana,
System.out is a java.lang.PrintStream. It has a println(char) method. So that gets called in your first example and it gets printed as a char.

By contrast, the later example calls the + operator first which treats it as an ASCII number and adds.
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you do arithmetic on chars they are promoted to ints, so '1' + '1' becomes (int) '1' + (int) '1' . And that is the same as 49 + 49.

Look at JLS 5.6.2.
 
Dana Ucaed
Ranch Hand
Posts: 406
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, so the type is important.

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!