File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString()

 
mansi gupte
Ranch Hand
Posts: 72
  • 0
  • 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
Pie
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • 0
  • 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
  • 0
  • 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".
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic