Java Reference
In-Depth Information
arguments; but if the result of invoking the toString method is null , then the string "null" is
used instead.
So what is the behavior of invoking toString on a non-null char array? Arrays inherit the
toString method from Object [JLS 10.7], whose specification says, "Returns a string consisting of
the name of the class of which the object is an instance, the at-sign character '@' , and the unsigned
hexadecimal representation of the hash code of the object" [Java-API] . The specification for
Class.getName says that the result of invoking this method on the class object for char[] is the
string "[C" . Putting it all together gives the ugly string printed by our program.
There are two ways to fix it. You can explicitly convert the array to a string before invoking string
concatenation:
System.out.println(letters + " easy as " +
String.valueOf(numbers));
Alternatively, you can break the System.out.println invocation in two to make use of the char[]
overloading of println :
System.out.print(letters + " easy as ");
System.out.println(numbers);
Note that these fixes work only if you invoke the correct overloading of the valueOf or println
method. In other words, they depend critically on the compile-time type of the array reference. The
following program illustrates this dependency. It looks as though it incorporates the second fix
described, but it produces the same ugly output as the original program because it invokes the
Object overloading of println instead of the char[] overloading:
// Broken - invokes the wrong overloading of println!
class Abc {
public static void main(String[] args) {
String letters = "ABC";
Object numbers = new char[] { '1', '2', '3' };
System.out.print(letters + " easy as ");
 
 
Search WWH ::




Custom Search