Junior — Middle
Can you explain what the toString method does in Java?
sobes.tech AI
Answer from AI
In Java, the toString() method is intended 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.
Classes often override toString() to return a more informative description of the object, useful for debugging and logging.
Example:
public 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 + "}";
}
}
// Usage:
Person p = new Person("Alice", 30);
System.out.println(p.toString()); // Outputs: Person{name='Alice', age=30}
Thus, toString() helps obtain a human-readable representation of the object.