Printing char arrays in Java

Solution is to use new String(c):

System.out.println("" + new String(c));

And the "" + is really bogus and should be removed.

Below is why you get what you get.


System.out is a PrintStream. println() has an overload for println(char[] x):

Prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println().


"" + c is string concatenation, which is defined 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.

And JLS 5.1.11 String Conversion says:

[…] the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments […]

toString() is not defined for arrays, so the Object.toString() method is invoked:

The toString method for class Object 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. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

Which is why you get something like [[email protected] when you do string concatenation.

Leave a Comment