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?
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
It would print some of the string you are looking for.
,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.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)':
One call is
PrintStream.println(char[])
the other call isPrintStream.println(String)
.This is because the JVM first evaluates
"" + c
. This is done by evaluating"" + c.toString()
which is identically toc.toString()
.So, your calls are equivalent to:
And these two calls are different.
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,
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:
Solution is to use
new String(c)
:And the
"" +
is really bogus and should be removed.Below is why you get what you get.
System.out
is aPrintStream
.println()
has an overload forprintln(char[] x)
:"" + c
is string concatenation, which is defined in JLS 15.18.1 String Concatenation Operator+
:And JLS 5.1.11 String Conversion says:
toString()
is not defined for arrays, so theObject.toString()
method is invoked:Which is why you get something like
[C@659e0bfd
when you do string concatenation.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)