toString()

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • toString() is a method in the Object class used to get a string representation of an object.
  • By default, it prints the class name and memory address hash (e.g., Person@2f92e0f4).
  • You should almost always override it to print the actual state/data of your object.

Concept

Whenever you try to print an object using System.out.println(myObject), Java automatically calls myObject.toString() behind the scenes.

If you don’t override it, the default implementation from java.lang.Object looks like this:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This is useless for debugging. Overriding it allows you to output human-readable JSON-like or structured strings representing your data.

Examples

class User {
    private String username;
    private int id;

    public User(String username, int id) {
        this.username = username;
        this.id = id;
    }

    // Overriding the default Object.toString()
    @Override
    public String toString() {
        return "User { id = " + id + ", username = '" + username + "' }";
    }
}

public class ToStringExample {
    public static void main(String[] args) {
        User u = new User("alice_99", 402);
        
        // This automatically invokes u.toString()
        System.out.println(u); 
        // Output: User { id = 402, username = 'alice_99' }
    }
}

Interview Questions

Q: Why is toString() important in Java?
A: It is critical for logging and debugging. When an exception occurs or when you log the state of an application, printing objects directly is common. If toString() is not overridden, logs will just contain meaningless memory hashes instead of the actual data that caused the bug.

Q: Can toString() return null?
A: Technically yes, the method signature allows returning null. However, it is a terrible practice and violates the expected contract. It should always return a non-null String representation.