Sobes.tech
Junior — Middle

What is the role of the toString method in a class or object?

sobes.tech AI

Answer from AI

The toString method in Java is used to obtain a string representation of an object. By default, it is defined in the Object class and returns a string containing the class name and the object's hash code.

Overriding toString in your classes allows:

  • Conveniently outputting the object's contents for debugging and logging.
  • Representing the object in a human-readable form.

Example of overriding:

public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{name='" + name + "', age=" + age + "}";
    }
}

Now calling toString on a User object will return an informative string, for example: User{name='Ivan', age=30}.

What is the role of the toString method in a class or… - sobes.tech