This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes toString() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "toString() " Watch "toString() " New topic
Author

toString()

mansi gupte
Ranch Hand

Joined: Dec 30, 2008
Posts: 72
toString() method , can someone explain its use with a simple practical/ day to day example?
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

You usually return some meaningful content from toString :

This method will automatically be called when used with methods such as System.out.println :


[My Blog]
All roads lead to JavaRanch
Balagopal Kannampallil
Ranch Hand

Joined: Oct 18, 2004
Posts: 136

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".

SCJP 5.0 and now fighting with ExtJS
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: toString()