Printing char arrays in Java

2020-05-27 10:45发布

If I print out a char array normally

char[] c = new char[]{'3','b','o'};
System.out.println(c); //prints 3bo

the output is a string. However, if I concatenate a String it prints the array memory location.

System.out.println("" + c); //prints [C@659e0bfd

I would have expected it to print as a String and I'm sure why this behavior happens. Any explanations?

标签: java arrays
7条回答
狗以群分
2楼-- · 2020-05-27 11:02

In the first case, you have an instance in a print stream. In the second case, you have the array concatenated with a string. If you did something like

System.out.println("" + c[0]); // or whatever number you put in there

It would print some of the string you are looking for.

String stringfromArray = "" + new String(c);

,would function more like what you are looking for in the second part of your question, but you don't need to do the "" + part.

查看更多
干净又极端
3楼-- · 2020-05-27 11:04

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;
    }
}
查看更多
聊天终结者
4楼-- · 2020-05-27 11:09

One call is PrintStream.println(char[]) the other call is PrintStream.println(String).

This is because the JVM first evaluates "" + c. This is done by evaluating "" + c.toString() which is identically to c.toString().

So, your calls are equivalent to:

System.out.println(c);
System.out.println(c.toString());

And these two calls are different.

查看更多
走好不送
5楼-- · 2020-05-27 11:10

All of the above are great solutions and explanations. However, there is also another way to 'bypass' this problem:

You can use two print statements, more specifically,

System.out.print("");
System.out.print(c);

This way they will be on the same line (b/c print does not use line feed to go to the next line) and you will not have to deal with any complications because of String concatenations.

For more information, see the Print Stream Documentation by Oracle . Here is the documentation portion for print when a char[] is passed as the argument:

public void print(char[] s)

Prints an array of characters. The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

查看更多
老娘就宠你
6楼-- · 2020-05-27 11:12

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.

查看更多
可以哭但决不认输i
7楼-- · 2020-05-27 11:12

the array of char can directly output,because it will insist on outputing untill the value is null And the array of char cannot use the way of toString(),because it will only get the memory location,so you can new String(the array of char)

查看更多
登录 后发表回答