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 [C@659e0bfd when you do string concatenation.


When you call System.out.println(char []array) the PrintStream class writes the chars (one of its overloads handles the job).

But for the second case, java converts the char array to string by calling its toString method which is a regular array toString method. And concatenating it with empty string, you receive the array signature [C*.... This is an expected and normal behavior.

Edit Here is the PrintStream code that gets eventually called when you call 'System.out.println(c)':

 private void write(char buf[]) {
    try {
        synchronized (this) {
            ensureOpen();
            textOut.write(buf);
            textOut.flushBuffer();
            charOut.flushBuffer();
            if (autoFlush) {
                for (int i = 0; i < buf.length; i++)
                    if (buf[i] == '\n')
                        out.flush();
            }
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}

Simplest form is:

Arrays.toString(c);

and if it is a 2D array, then use Arrays.deepToString as follows:

Arrays.deepToString(twoDArray);

Tags:

Java

Arrays