Adding toString method for custom objects

suggest change

Suppose you have defined the following Person class:

public class Person {

    String name;
    int age;
    public Person (int age, String name) {
        this.age = age; = 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:


Live Demo on Ideone

you’ll get an output similar to the following:


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:

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

Now the output will be:

My name is John and my age is 25

You can also write


Live Demo on Ideone

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

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents