Java Reference
In-Depth Information
< Day Day Up >
Puzzle 12: ABC
This puzzle asks the musical question, What does this program print?
public class Abc {
public static void main(String[] args) {
String letters = "ABC";
char[] numbers = { '1', '2', '3' };
System.out.println(letters + " easy as " + numbers);
}
}
Solution 12: ABC
One would hope that the program prints
ABC easy as 123
. Unfortunately, it does not. If you ran it,
you found that it prints something like
ABC easy as [C@16f0472
. Why is the output so ugly?
Although
char
is an integral type, many libraries treat it specially, because
char
values usually
represent characters rather than integers. For example, passing a
char
value to
println
prints a
Unicode character rather than its numerical code. Character arrays get similar special treatment:
The
char[]
overloading of
println
prints all of the characters contained in the array, and the
char[]
overloadings of
String.valueOf
and
StringBuffer.append
behave analogously.
The string concatenation operator, however, is not defined in terms of these methods. It is defined
to perform
string conversion
on both of its operands and then to concatenate the resulting strings.
String conversion for object references, which include arrays, is defined as follows [JLS 15.18.1.1]:
If the reference is
null
, it is converted to the string
"null"
. Otherwise, the conversion is
performed as if by an invocation of the
toString
method of the referenced object with no
Search WWH ::
Custom Search