Sunday, 25 March 2012

How and Why to override the toString() method in Java

Object class has following five non final methods.

1. clone()
2. equals(Object obj)
3. finalize()
4. hashCode()
5. toString()

Every Java class has Object as a super class so by default all above methods are provided in every java class. In this article we will discuss in detail the concepts of toString() method. We will discuss why it is necessary to override toString method and how we can override it.

The toString() method in the Object class is used to display some information regarding any object.The toString method is widely implemented. It provides a simple, convenient mechanism for debugging classes during development.When debugging, you want to be able to print a human readable representation of your object.It is widely used for logging.
The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method.



Default implementation of toString() in Object class


The Object class provided toString method returns a String with the format, Class name followed by the @ symbol, followed by the unsigned hexadecimal representation of the object’s hashCode.See one example
public class Main {

 public static void main(String args[]) {
  Student s1 = new Student(10, "Suresh", "CS");
  System.out.println("s1=" + s1);

 }
}

class Student {
 int rollno;
 String name;
 String dept;

 public Student(int rollno, String name, String dept) {
  this.rollno = rollno;
  this.name = name;
  this.dept = dept;
 }

}

The output is


s1=Student@9304b1

Why to override toString() method 


In the above example you have seen that Object class provided toString method not giving any meaningful information regarding the object.We have to override the toString method in such a way that it is giving some meaningful information regarding the object,I.e. about the state of the object.See the example

public class Main {
  public static void main(String args[]) {
   Student s1 = new Student(10, "Suresh", "CS");
   System.out.println("s1=" + s1);
  }
}

class Student {
 int rollno;
 String name;
 String dept;

 public Student(int rollno, String name, String dept) {
  this.rollno = rollno;
  this.name = name;
  this.dept = dept;
 }

 @Override
 public String toString() {
  return "Student [rollno=" + rollno + ", name=" + name + ", dept="
    + dept + "]";
 }

}


The output is
s1=Student [rollno=10, name=Suresh, dept=CS]

Notice that overridden toString method is called automatically when the object s1 is passed as an argument to println() method.The overridden toString method is giving meaningful information about the state of the object s1.


Override toString() In Eclipse and Netbeans

In Netbeans

1) Write your Class.
2) Right click + insert code + Generate toString().

In Eclipse

1) Write your Class.2) Go to Source Menu + Generate toString().


Generate toString() using Apache ToStringBuilder

Rather than using Eclipse generated toString() method we could use the Apache Commons ToStringBuilder.
This class enables a good and consistent toString() to be built for any class or object. This class aims to simplify the process by:
  • allowing field names
  • handling all types consistently
  • handling nulls consistently
  • outputting arrays and multi-dimensional arrays
  • enabling the detail level to be controlled for Objects and Collections
  • handling class hierarchies

See one example


import org.apache.commons.lang3.builder.ToStringBuilder;

public class Main {

 public static void main(String args[]) {
  Student s1 = new Student(10, "Suresh", "CS");
  System.out.println("s1=" + s1);

 }
}

class Student {
 int rollno;
 String name;
 String dept;

 public Student(int rollno, String name, String dept) {
  this.rollno = rollno;
  this.name = name;
  this.dept = dept;
 }

 @Override
 public String toString() {

  ToStringBuilder builder = new ToStringBuilder(this);

  builder.append("rollno", rollno);
  builder.append("name", name);
  builder.append("dept", dept);
  return builder.build();
 }

}
The output is
s1=Student@69b332[rollno=10,name=Suresh,dept=CS]

No comments:

Post a Comment