Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes toString Clarification Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "toString Clarification" Watch "toString Clarification" New topic
Author

toString Clarification

Mitch Krah
Ranch Hand

Joined: Sep 06, 2004
Posts: 41
Can someone provide clarification of the toString method and overriding it in classes to print "meaningful" information? I have been asked to implement the toString method in classes but can only find a paragraph on this method in 2 different books. Any additional/practicle information would be appreciated.

Thank you,
M
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30370
    
150

Mitch,
By default the toString() method outputs a hash representing the memory address. Often, we overwrite this to contain useful information about the state of the object (such as the values of it's fields.) As an example,


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Mitch Krah
Ranch Hand

Joined: Sep 06, 2004
Posts: 41
Thank you.

And then, how do you call the toString from another class?

M
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
either
System.out.println( myObject );
or
System.out.println( myObject.toString() );

It makes no never mind.


Mike Gershman
SCJP 1.4, SCWCD in process
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Appending an object reference to a String using the + operator will call toStrnig() on the reference (or append "null" if it's null) for you.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: toString Clarification