Adding toString() method for custom objects


Suppose you have defined the following Person class:

public class Person
{
    String fullName;
    int personAge;
 
    public Person(int personAge, String fullName)
    {
        this.personAge = personAge;
        this.fullName = fullName;
    }
}

If you instantiate a new Person object:

Person individual = new Person(30, "Deva");

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

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

you'll get an output similar to the following:

//YourPackageName.ClassName@hashcode
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:

public class Person
{
    String fullName;
    int personAge;
 
    public Person(int personAge, String fullName)
    {
        this.personAge = personAge;
        this.fullName = fullName;
    }
 
	@Override
	public String toString()
	{
		return "My name is " + this.fullName + " and my age is " + this.personAge;
	}
}
class Sample
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Person individual = new Person(30, "Deva");
		System.out.println(individual);
	}
}

Now the output will be:

My name is Deva and my age is 30

Basic Programs