How to override the toString() method in Java

All the classes in Java extendinherit from a parent class known as the Object class, and this superclass has methods like clone(), equals(), toString(), etc., that are automatically inherited by all the children or subclasses. So, if you try to print an object of these classes, the Java compiler internally invokes the default toString() method on the object and will generally provide the string representation of the object, which will be printed on the console in the format [ClassName@hashcode()], e.g., [Object@19821f].

However, this output doesn’t seem readable. We want to get understandable information (string representation) of an object. We can override the toString() method in our class to print a proper text output. We can also provide any additional information for the property or field of an object when overriding the toString() method.

By overriding the toString() method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.

Code

Below is an example of a student class that does not override the default toString() method.

class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
// Driver class to test the Student class
public class Demo {
public static void main(String[] args) {
Student s = new Student(101, "James Bond");
System.out.println("The student details are: "+s);
}
}

Expected output

The student details are: Student@28d93b30

The code below overrides the default toString() method.

class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return id + " " + name;
}
}
// Driver class to test the Student class
public class Demo {
public static void main(String[] args) {
Student s = new Student(101, "James Bond");
System.out.println("The student details are: "+s);
}
}

Expected output

The student details are: 101 James Bond

As you can see above, we can override the toString() method of the Student class to get a meaningful presentation of the object.

In conclusion, it’s a good idea to override toString(), as we get proper and customized output when an object is used. Overriding toString() also helps debug or log any null checks, concatenations, or string manipulations prior to printing an object’s attribute.

Free Resources