Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How toString() is automatically call inside println()

I just started learning Java. What I've learned about constructor is that :

  1. It will automatically run when an object is initialized.

  2. The name of the constructor has be the same as the class name.

Now, below is where I'm starting to get confused.

class Frog{

   public String toString() {
      return "Hello";
   }
}

public class App {

   public static void main(String[] args) {
      Frog frog1 = new Frog();
      System.out.println(frog1);
   }
}

My question : Since public String toString () is not a constructor, then why can it behave like constructor when I run the program. I thought It can only be run when I call it from the App class.

like image 532
Bernard Avatar asked Mar 21 '16 10:03

Bernard


2 Answers

Short answer: public frog1.toString() method call is used inside System.out.println(Object x) call stack.

But how? Let's find it out together :)

Take a look at the PrintStream class (which instance is used as System.out field value by default) source code and its println implementation that accepts Object argument:

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

And the String's valueOf method for argument with Object type is:

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

obj is frog1 in your case, its toString() method is called and returns "Hello" String instance for the console output)

like image 71
Cootri Avatar answered Nov 03 '22 02:11

Cootri


The "toString" is not behaving like a constructor; the reason why it is being called is the second line in your main method:

  System.out.println(frog1);

This invokes toString on frog1.

like image 36
Andrea Bergia Avatar answered Nov 03 '22 04:11

Andrea Bergia