• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why when I print an Object is the toString method called?  RSS feed

 
Ioanna Katsanou
Ranch Hand
Posts: 131
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello I cannot understand
why when I write:


or

why is the toString method called???

thanks in advance

 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's the way System.out.println() was written.  It calls the toString() method on the object that is passed to it.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because that's how the library is implemented.  The call is actually done from the String class: println(obj) calls String.valueOf(obj) which first checks for null. If the reference is null, the literal "null" will be returned, otherwise the object's toString() value is returned. This is why you should avoid calling String.valueOf() in your toString() implementations otherwise you could get into an endless recursion and blow the stack with a StackOverflowError.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!