Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does a toString method automatically get run without being called when printing an object to the console?

I was wondering exactly how the toString() method runs without being called when printing out a object.

Code visualization:

Without toString() method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Shop
{

  Shop()
  {
  }

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

Result: Shop@3421

With toString() method:

public class Shop
{

  Shop()
  {
  }

  public void toString()
  {
    return "I am a shop";
  }

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

Result: I am a shop. The toString method ran but was never called? How?

>Solution :

toString does get called – just not by you! println takes an Object as its argument. As Object has a toString method (the default of which you saw when running your first snippet) the println method will call the passed Object‘s toString before putting the output into System.out.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading