Purpose of Overriding toString() Method in Java

Amir
Amir
Purpose of Overriding toString() Method in Java

What is the purpose of toString() method in Java?

If we want to represent an object of a class as a String, then we can use the toString() method which returns a textual representation of the object.

When you print an object, by default the Java compiler invokes the toString() method on the object. So by overriding the toString() method, we can provide meaningful output.

Let’s see this concept in the following example:

Overriding toString() Method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package io.devqa.tutorials;

public class ToStringExample {

    private String firstName;
    private String lastName;
    private String email;

    public ToStringExample() {

    }
    
    public String getFirstName() {
        return firstName;
    }
        
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
        
    public String getLastName() {
        return lastName;
    }
        
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
        
    public String getEmail() {
        return email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("First name : ").append(this.firstName).append("\n");
        sb.append("Last name : ").append(this.lastName).append("\n");
        sb.append("Email : ").append(this.email).append("\n");
        return sb.toString();
    }

    public static void main(String args[]) {
        ToStringExample example = new ToStringExample();
        example.setFirstName("Testing");
        example.setLastName("Tester");
        example.setEmail("testing@tester.com");

        System.out.println(example);
    }
}

The above code outputs the following:

1
2
3
First name : Testing
Last name : Tester
Email : testing@tester.com

If we didn’t override the toString() method, the output would have been

1
io.devqa.tutorials.ToStringExample@60e53b93

As can be seen, by overriding the toString() method, we can output meaningful presentation of the object.

See also