Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString()

 
mansi gupte
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
toString() method , can someone explain its use with a simple practical/ day to day example?
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You usually return some meaningful content from toString :

This method will automatically be called when used with methods such as System.out.println :
 
Balagopal Kannampallil
Ranch Hand
Posts: 136
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sure that most of the developers have gone through this issue. Take an example, you have a class namely MyClass. You make a new instance

Now you try to print mymy, the result you will be seeing is the class name followed by weird characters like "MyClass@10b62c9" (Something like this). This is because you have not overridden the toString() method in your MyClass class. So MyClass will use the toString() method of its superclass Object.
So if you want to see some meaningful things in place of "MyClass@10b62c9" when you print mymy. You will have to override toString() method in MyClass and return some meaningful string. For example:

Now if you print mymy, you will see "Hi I am MyClass".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic