I have following code snippet and their output below:
String
System.out.println("A"); // output A
System.out.println("B"); // output B
System.out.println("A" + "B"); // output AB
char
System.out.println('A'); // output A
System.out.println('B'); // output B
System.out.println('A' + 'B'); // output 131
What is the reason that char's output is getting printed as string for single char value where as integer if + operator is used? I do not find this answer in this post The concatenation of chars to form a string gives different results
What is the reason that char's out is getting printed as string for single char value where as integer if + operator is used?
There's no +
operator for char
, so both operands are being promoted to int
(values 65 and 66 respectively, in the normal way that char
is converted to int
), and the result is int
as well. Whereas in your string example, it's using the string concatenation operator.
Basically, this is normal operator overload resolution, using the +
operators described in JLS 15.18.
See more on this question at Stackoverflow