File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "toString Clarification" Watch "toString Clarification" New topic

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,
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 32818

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,

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, 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?

Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
System.out.println( myObject );
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.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: toString Clarification
It's not a secret anymore!