问题
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?
回答1:
However I'm wondering if I just got garbage?
No, you got the result of Object.toString(), which isn't overridden in arrays:
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())
So it's not garbage, in that it has a meaning... but it's not a particularly useful value, either.
And your bonus question...
How do you correctly print a character array in java?
Call Arrays.toString(char[]) to convert it to a string... or just
System.out.println(hello);
which will call println(char[])
instead, which converts it into a string. Note that Arrays.toString
will build a string which is obviously an array of characters, whereas System.out.println(hello)
is broadly equivalent to System.out.println(new String(hello))
来源:https://stackoverflow.com/questions/13764700/what-does-the-output-of-a-printed-character-array-mean