Nothing important.

The toString() method is provided by all Java Object types, which means it is available to call on all classes.  But when should it be used?

The Object class provides a default toString() method that displays some basic information about the class.  It is tempting to make toString() a core part of an application, turning model objects into a specially formatted String so it can be displayed on a user screen.

However the convention is that toString() should only be used to provide a simple text representation of the class contents to display in debug messages or logs.

toString() does not have to be implemented at all, but if it is it should produce a nicely formatted String that will fit onto one line of text, without carriage returns as follows:

public String toString()
{
    return "imageId=" + id  
         + ", filename=" + fileName  
         + ", description=" + description
         + ", keywords=" + keywords  
         + ", author=" + author
         + ", application=" + application
         + ", status=" + status  
         + ", creationDate=" + creationDate
         + ", accessCount=" + accessCount  
         + ", accessDate=" + accessDate
         + ", accessGroup=" + accessGroup;   
}

Produces “imageId=1772, filename=foo.gif, description=wedding photo...etc”

Before you comment, optimizing a toString() method with StringBuilder is not necessary since it is for debug only and will rarely be called.

Any other activity that is not related to displaying debug text (like writing to a stream or formatting for display on a user screen) should be done using a method with a specialized name such as toXml() or formatForUserDisplay() respectively.

Another reason not to use toString() for anything important is that you can't require anyone to implement it using an interface.  Developers can choose to ignore it because an Object always provides a default toString() method and all classes naturally derive from Object.  So the method requirement can never be enforced.  If you want to make developers implement a particular method, don't call it toString().

Tip: Never rely on toString() to do anything important – popular culture suggests it is only for playing around.

blog comments powered by Disqus