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;
        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.

Feedback about page:

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


Strings:
* Adding toString method for custom objects

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap