36. What is the purpose of toString() method?

What is the purpose of toString() method?

  • The string return when we log an instance of a class is the name of class and hashcode of that instance
  • If you want to wirte the content of that instance, you must override the toString method

Example:

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

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

// Override toString method
@Override
public String toString() {
return “Person{name='” + name + “‘, age=” + age + “}”;
}

public static void main(String[] args) {
Person person = new Person(“Alice”, 30);
System.out.println(person); // Automatically calls toString() method
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *