Chapter 6 - Java for Beginners Course

Object String Representation

Another of the standard methods that comes from the Object class allows us to provide a String representation of our objects. This method is aptly named toString and its signature is:

public String toString();

The toString method is meant to give a human-readable representation of the object. Java will use this method internally when including the object in string concatenation operations, for example, if you do:

DictionaryEntry walk = new DictionaryEntry("walk", "definition of walk");
String result = "The object is: " + walk;

Internally, the compiler will call walk.toString() as part of the String concatenation in the second line.

The toString method shouldn’t be used to serialize/transform the object into different formats. For example, you shouldn’t use the toString method to serialize an object into JSON/XML or other formats as it isn’t meant for that purpose.

To continue with our DictionaryEntry class, we’ll use the same final class from our Object Equality sections and override the toString method:

public class DictionaryEntry {
    private final String word;

    private final String definition;

    public DictionaryEntry(String word, String definition) {
        this.word = word;
        this.definition = definition;
    }

    @Override
    public String toString() {
        return "DictionaryEntry [word=" + word + ", definition=" + definition + "]";
    }

	//...
}

Let’s give this a go:

In the example code run the JavaObjectToStringApp
DictionaryEntry walk = new DictionaryEntry("walk", "definition of walk");
String result = "The object is: " + walk;
System.out.println(result);

Output:

The object is: DictionaryEntry [word=walk, definition=definition of walk]

The default behavior of toString

If we don’t provide an override to the toString method, by default the string representation that is returned by the Object.toString method is a combination of two things:

  • The name of the class, and,

  • The hash code of the object in hexadecimal format

Both of these will be separated by an @ symbol.

For example, let’s assume we remove our toString override from our DictionaryEntry class and if we executed the same example above:

DictionaryEntry walk = new DictionaryEntry("walk", "definition of walk");
String result = "The object is: " + walk;
System.out.println(result);

Output:

The object is: io.jcoder.tutorials.ch06.objecttostring.DictionaryEntry@3791e8
The hash code you get is very likely to be different to the one we show above.

Some common usages of toString

A common usage of the toString method is when writing application logs that will help with the investigation of issues of the systems at runtime.

They’re also used to help in the debugging of applications, as it is easier to understand DictionaryEntry [word=walk, definition=definition of walk] rather than io.jcoder.tutorials.ch06.objecttostring.DictionaryEntry@3791e8.