Sobes.tech
Junior

What does the toString() method do in Java?

sobes.tech AI

Answer from AI

The toString() method in Java is intended to obtain a string representation of an object. By default, it returns a string containing the class name of the object, the @ symbol, and the hexadecimal representation of the object's hash code (e.g., java.lang.Object@1a2b3c4d).

This method is often overridden in user-defined classes to provide a more informative representation of the object, such as displaying the values of its fields. This is useful for debugging, logging, or simply outputting the object in a human-readable form.

Examples of usage:

// Default behavior of toString()
Object obj = new Object();
System.out.println(obj.toString()); // Output: java.lang.Object@...

// Overriding toString() in a user-defined class
class Person {
    private String name;
    private int age;

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

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

Person person = new Person("Alice", 30);
System.out.println(person.toString()); // Output: Person{name='Alice', age=30}
System.out.println(person); // Same as above, as System.out.println() calls toString()