Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How an object will call toString method implicitly?

Tags:

java

If I am printing an object of the class then it is printing the toString() method implementation even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?

like image 718
user2475808 Avatar asked Jun 11 '13 18:06

user2475808


2 Answers

You're not explicitly calling toString(), but implicitly you are:

See:

System.out.println(foo); // foo is a non primitive variable

System is a class, with a static field out, of type PrintStream. So you're calling the println(Object) method of a PrintStream.

It is implemented like this:

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

As we see, it's calling the String.valueOf(Object) method.
This is implemented as follows:

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

And here you see, that toString() is called.

like image 92
jlordo Avatar answered Oct 27 '22 12:10

jlordo


Every object in Java IS-A(n) Object as well. Hence, if a toString() implementation has not been provided by a class the default Object.toString() gets invoked automatically.

Object.toString()'s default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.

even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?

toString() is one of the few methods (like equals(), hashCode() etc.) that gets called implicitly under certain programmatic situations like (just naming a few)

  • printing an object using println()
  • printing a Collection of objects (toString() is invoked on all the elements)
  • concatenation with a String (like strObj = "My obj as string is " + myObj;)
like image 36
Ravi K Thapliyal Avatar answered Oct 27 '22 13:10

Ravi K Thapliyal