views:

187

answers:

4

Here's the code snippet:

public static void main (String[]arg) 
{
    char ca = 'a' ; 
    char cb = 'b' ; 
    System.out.println (ca + cb) ; 
}

The output is:

195

Why is this the case? I would think that 'a' + 'b' would be either "ab" , "12" , or 3.

Whats going on here?

+14  A: 

+ of two char is arithmetic addition, not string concatenation. You have to do something like "" + ca + cb, or use String.valueOf and Character.toString methods to ensure that at least one of the operands of + is a String for the operator to be string concatenation.

JLS 15.18 Additive Operators

If the type of either operand of a + operator is String, then the operation is string concatenation.

Otherwise, the type of each of the operands of the + operator must be a type that is convertible to a primitive numeric type, or a compile-time error occurs.

As to why you're getting 195, it's because in ASCII, 'a' = 97 and 'b' = 98, and 97 + 98 = 195.


This performs basic int and char casting.

 char ch = 'a';
 int i = (int) ch;   
 System.out.println(i);   // prints "97"
 ch = (char) 99;
 System.out.println(ch);  // prints "c"

This ignores the issue of character encoding schemes (which a beginner should not worry about... yet!).


As a note, Josh Bloch noted that it is rather unfortunate that + is overloaded for both string concatenation and integer addition ("It may have been a mistake to overload the + operator for string concatenation." -- Java Puzzlers, Puzzle 11: The Last Laugh). A lot of this kinds of confusion could've been easily avoided by having a different token for string concatenation.


See also

polygenelubricants
@abelenky, use lowercase letters `'a`, 'b'` for accuracy.
polygenelubricants
David: If you open "charmap", or "Character Map" in Windows, you'll see that the characters "a" and "b" have ASCII values 97 and 98, respectively. You might want to look-up "ASCII" in Wikipedia.
Andreas Rejbrand
is there a way to turn the ASCII numbers back into characters. like is there a method that takes 99 and returns 'c'?
David
@David: I gave example of basic casting.
polygenelubricants
+3  A: 

I don't speak Java, but 195 is 97 + 98 = the ASCII codes for a and b. So obviously, ca and cb are interpreted as their integer values, probably because of the + addition which does not seem to lead to a string concatenation automatically.

Pekka
+1  A: 

The + operator doesn't operate over characters like it does over strings. What's happening here is that a and b are being cast to their integer ASCII codepoints - 97 and 98 - and then added together.

Michael Petrotta
+3  A: 

If you want to have a String as result of the + operator you have to use type String as operands.

You should write:

public static void main (String[]arg) 
{
    String ca = "a" ; 
    String cb = "b" ; 
    System.out.println (ca + cb) ; 
}

The + operator applied on char operands behaves as the arithmetic sum.

Dj Gaspa