I’m moving from C to Java now and I was following some tutorials regarding Strings. At one point in the tutorials they showed instantiating a new string from a character array then printing the string. I was following along, but I wanted to print both the character array and the string so I tried this:
class Whatever {
public static void main(String args[]) {
char[] hello = { 'h', 'e', 'l', 'l', 'o', '.'};
String hello_str = new String(hello);
System.out.println(hello + " " + hello_str);
}
}
My output was something like this:
[C@9304b1 hello.
Clearly, this is not how you would print a character array in Java. However I’m wondering if I just got garbage? I read on some site that printing a character array give you an address, but that doesn’t look like an address to me… I haven’t found a lot online about it.
So, what did I just print?
and bonus questions:
How do you correctly print a character array in java?
No, you got the result of
Object.toString(), which isn’t overridden in arrays:So it’s not garbage, in that it has a meaning… but it’s not a particularly useful value, either.
And your bonus question…
Call
Arrays.toString(char[])to convert it to a string… or justwhich will call
println(char[])instead, which converts it into a string. Note thatArrays.toStringwill build a string which is obviously an array of characters, whereasSystem.out.println(hello)is broadly equivalent toSystem.out.println(new String(hello))