A very simple question. Does it have anything to do with performance? Something else?
System.out.println('c');
System.out.println("c");
Which, why?
System.out.println("Letter: " + "c");
System.out.println("Letter: " + 'c');
Which, why?
A very simple question. Does it have anything to do with performance? Something else?
System.out.println('c');
System.out.println("c");
Which, why?
System.out.println("Letter: " + "c");
System.out.println("Letter: " + 'c');
Which, why?
They are different things. "c" is a String object of length 1; 'c' is a char primitive value (one of the integer types in Java).
Part of why they seem interchangeable is because of Java's rules for string concatenation; the language defines aString + aChar to be the string that results from appending to aString the character represented by the UTF-16 value aChar. In your particular example, the expression "Letter: " + 'c' is treated as a compile-time constant String expression and evaluated by the compiler, not at run time. You can see this by compiling the code and looking at the resulting bytecode.
The Java Language Specification spells out what's going on. First, one reads in JLS §15.18.1 ("String Concatenation Operator +"):
If only one operand expression is of type
String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.The result of string concatenation is a reference to a
Stringobject that is the concatenation of the two operand strings.
Then in §5.1.11 we find (among other rules):
A value
xof primitive typeTis first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression (§15.9):
- ...
- If
Tischar, then usenew Character(x).- ...
This reference value is then converted to type
Stringby string conversion.
So in theory, the char constant 'c' is autoboxed to a Character object. However, in practice the compiler and the core classes take substantial liberties and generate much more efficient (but functionally equivalent) code.