Junior — Middle
What is the purpose of the toString method and how is it used in code?
sobes.tech AI
Answer from AI
The toString() method in Java is designed 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, which is usually not very informative.
Overriding toString() in your classes allows you to display the contents of an object in a human-readable form, which is 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("Ivan", 30);
System.out.println(p); // Will output: Person{name='Ivan', age=30}
Thus, toString() helps to obtain a human-readable description of the object.