Search code examples
javachartostring

Java char[] toString


I'm playing arround with char[] in Java, and using the folowing sample code:

char[] str = "Hello World !".toCharArray();
System.out.println(str.toString());
System.out.println(str);

I get the following output:

[C@4367e003
Hello World !

And I have some questions about it:

  1. What does [C@4367e003 stands for? Is it a memory address? What's the meaning of the digits? What's the meaning of [C@?

  2. I always thought that calling println() on an object would call the toString method of this object but it doesn't seems to be the case?


Solution

    1. [C means that it's a character array ([ means array; C means char), and @4367e003 means it's at the memory address[1] 4367e003. If you want a string that represents that character array, try new String(str).

    2. println is overloaded; there is also a println that accepts a character array. If you don't pass a primitive, String, or char[], it will then call toString on the object since there's a separate overload for System.out.println(Object). Here is the documentation for the specific method that takes a character array.

      Here are the overloads for println (straight from the docs):

      void println()
      void println(boolean x)
      void println(char x)
      void println(char[] x)
      void println(double x)
      void println(float x)
      void println(int x)
      void println(long x)
      void println(Object x)
      void println(String x)
      

      You can read more about overloading at the bottom of this tutorial.


    [1]: Technically, it's actually the hex representation of the object's hash code, but this is typically implemented by using the memory address. Note that it's not always really the memory address; sometimes that doesn't fit in an int. More info in this quesiton.