Overriding toString() method in Java


toString() method 

In Java if you want to represent any object as a string, toString() method comes into picture.

The toString() method returns the string representation of the object.

If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

// file name: StudentDemo.java
class StudentDemo{

 int rollno;  
 String name;  
 String city;    

 StudentDemo(int rollno, String name, String city){  

 this.rollno=rollno;  
 this.name=name;  
 this.city=city;  

 }  

   public static void main(String args[]){  

   StudentDemo s1=new StudentDemo(101,"Raj","lucknow");  

   StudentDemo s2=new StudentDemo(102,"Vijay","ghaziabad");       

   System.out.println(s1);//compiler writes here s1.toString()  

   System.out.println(s2);//compiler writes here s2.toString()  

 }  

} 

Output:
Student@1fee6fc
Student@1eed786

The output is, class name, then ‘@’ sign, and at the end hashCode of object. All classes in Java inherit from the Object class, directly or indirectly. The Object class has some basic methods like clone(), toString(), equals(),.. etc. The default toString() method in Object prints “class name @ hash code”. We can override toString() method in our class to print proper output. For example, in the following code toString() is overridden to print “Real + i Imag” form.

 

// file name: StudentDemo.java

class StudentDemo{

 int rollno;  
 String name;  
 String city;    

 StudentDemo(int rollno, String name, String city){  

 this.rollno=rollno;
 this.name=name;  
 this.city=city;  
 }     

 public String toString(){//overriding the toString() method  

  return rollno+" "+name+" "+city;  

 }  

 public static void main(String args[]){  

   StudentDemo s1=new StudentDemo(101,"Raj","lucknow");  
   StudentDemo s2=new StudentDemo(102,"Vijay","ghaziabad");       

   System.out.println(s1);//compiler writes here s1.toString()  
   System.out.println(s2);//compiler writes here s2.toString()  

 }  

}  

Output:

101 Raj lucknow
102 Vijay ghaziabad

In general, it is a good idea to override toString() as we get get proper output when an object is used in print() or println().

Related Articles

post a comment