toString method of Object class in Java

This is very important method. I have seen in multiple code review where developers call toString method to print content of object. Actually you don't have to call this method explicitly. This method is automatically called when you print object of any class. What I meant for "content of object" is values of instance variable or any meaningful human readable information of an object. 

But toString method of object class does not return human readable information about object. It returns name of the class and hexadecimal representation of hashcode.  This information is useless for human. This information does not say anything about an object. 

Below is code snippet of toString method from Object class-

public String toString() {
  return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Let's see how toString method print information of an object by below example -

public class Person {
 private Integer id;
 private String name;
 public Person(Integer id, String name) {
  this.id = id;
  this.name = name;
 }

 public static void main(String[] args) {
  Person person = new Person(1, "Parth");
  System.out.println(person);
 }
 
}
Output: Person@659e0bfd

As you can see output of above program, this output not human readable form. 

We need to override toString method in Person class to print meaningful information. 
Example - 

public class Person {
 private Integer id;
 private String name;
 public Person(Integer id, String name) {
  this.id = id;
  this.name = name;
 }
  
 @Override
 public String toString() {
  return "Person [id=" + id + ", name=" + name + "]";
 }

 public static void main(String[] args) {
  Person person = new Person(1, "Parth");
  System.out.println(person);
 } 
}
Output: Person [id=1, name=Parth]
Above program prints values of id and name variables because toString method is overridden in Person class. Here we are not calling toString method explicitly. We are just printing object of Person class and toString method getting called internally.

Comments

Popular posts from this blog

Data types and Literals in Java

How to define Auxiliary Constructor in case class in Scala

Dependency Injection in Spring framework