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?
+of twocharis arithmetic addition, not string concatenation. You have to do something like"" + ca + cb, or useString.valueOfandCharacter.toStringmethods to ensure that at least one of the operands of+is aStringfor the operator to be string concatenation.JLS 15.18 Additive Operators
As to why you’re getting 195, it’s because in ASCII,
'a' = 97and'b' = 98, and97 + 98 = 195.This performs basic
intandcharcasting.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