Search code examples
javaobject-to-string

Why print statement calls **toString** method in java?


Why the following code segment auto calls toString() method?

Code:

public class Demo {
   public Demo() {
    System.out.println(this); // Why does this line automatically calls toString()?
    }

   public static void main(String[] args) {
    Demo dm = new Demo();
   }
}

Solution

  • println is overloaded for various types, the one you are invoking is:

    java.io.PrintStream.println(java.lang.Object)

    Which looks like this:

    public void println(Object x) {
      String s = String.valueOf(x);
      synchronized (this) {
        print(s);
        newLine();
      }
    }
    

    And String.valueOf looks like this:

    public static String valueOf(Object obj) {
      return (obj == null) ? "null" : obj.toString();
    }
    

    So you can see it calls toString() on your object. QED