java – Converting char array to string

Question:

I don't understand why this is the conclusion:

for (int i = 0; i < temp.length; i++) {
    System.out.print(temp[i]);
}

Very different from this one:

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

In the first case, the array of characters is displayed as it should, and in the second, it shows not characters, but bytes. How then to rewrite the char 's array into a string correctly?

Answer:

An array of characters ( char[] ), not a string class ( String ).

To convert an array of characters to a string, you need to create this string from the array of characters.

String myStr = new String(temp);

And then output it as a regular string

System.out.println(myStr);

UPD by Artem Konovalov

The .toString() method returns the class representation + the object hashcode in hexadecimal notation

return getClass().getName() + "@" + Integer.toHexString(hashCode());

Scroll to Top