The toString() Method

Things To Do Later

The toString() Method

As mentioned previously, the toString() method is already defined in Java and is used to return a "string representation" of an object. In other words, it returns your object as a String. For example, a Course class might have the toString() defined to return the course code followed by a colon and the course name, so that if you had a course object for PROG10082, your course object as a String would be "PROG10082: Object Oriented Programming 1".

When you add your own toString() method to your classes, it must always be defined as:

public String toString() { ... }

In addition, your method must return a String object. For example, the toString() method for the Course class might be defined as:

public String toString() {
    return courseCode + ": " + courseName;
}

In designing a class, you need to think of what instances of your classes should "look like" as Strings. Then you can define an appropriate toString() method.

Implicit Call to toString()

When your class has a toString() method, it allows you do print objects to the console using print() or println() in this way:

Circle circleObject = new Circle();
System.out.println(circleObject);

In this example, the println() method will look inside the circle for a toString() definition. If it finds one, it will execute that method, take the String object that method returns, and send that String to the println() method. This will show your toString() method's return value on the console.

If you don't have a toString() in your class, Java will use the default toString() definition. The default toString() method returns a String that consists of the name of the class that the object is an instance of, the @ symbol, and then the objects hash code in hexadecimal form.

A hash code is an objects identifier (or ID). Objects are referenced by a hash table in memory so that they can be accessed quickly. For more information, check out Java Glossary: has code.

For example, if your circle class didn't have a toString(), then the previous code segment might print something like:

Circle@82ba41