What is toString in Java?

In Java, the toString() method is a built-in method defined in the Object class, which is the superclass of all classes in Java. This method is used to create a string representation of an object. When you attempt to print an object, the toString() method is automatically called to convert the object into a string format that is more human-readable.

For custom classes, overriding the toString() method is a common practice to provide a meaningful string representation of the object's state or attributes.

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 + "}"; } } public class Main { public static void main(String[] args) { Person person = new Person("Alice", 30); System.out.println(person); // This will call person.toString() } }

toString Java Object class string representation overriding custom classes