Looking for java Answers? Try Ask4KnowledgeBase
Looking for java Keywords? Try Ask4Keywords

Java Language Adding toString() method for custom objects


Example

Suppose you have defined the following Person class:

public class Person {

    String name;
    int age;
    
    public Person (int age, String name) {
        this.age = age;
        this.name = name;
    }
}

If you instantiate a new Person object:

Person person = new Person(25, "John");

and later in your code you use the following statement in order to print the object:

System.out.println(person.toString());

Live Demo on Ideone

you'll get an output similar to the following:

Person@7ab89d

This is the result of the implementation of the toString() method defined in the Object class, a superclass of Person. The documentation of Object.toString() states:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

So, for meaningful output, you'll have to override the toString() method:

@Override
public String toString() {
    return "My name is " + this.name + " and my age is " + this.age;
}

Now the output will be:

My name is John and my age is 25

You can also write

System.out.println(person);

Live Demo on Ideone

In fact, println() implicitly invokes the toString method on the object.