Sobes.tech
Junior — Middle

Explain the purpose of the toString() method in the Object class and its role in outputting information about an object.

sobes.tech AI

Answer from AI

The toString() method in the Object class is intended to return a string representation of the object. By default, it returns a string containing the class name and the hash code of the object, which is not always informative.

The role of the toString() method:

  • Allows obtaining a human-readable description of the object, useful for debugging and logging.
  • Often overridden in user-defined classes to output meaningful fields of the object.

Example of overriding:

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

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

Now, when printing a User object via System.out.println(user), an informative string with the name and age will be displayed.

Explain the purpose of the toString() method in the… - sobes.tech