Tuesday 8 March 2016

Overriding toString() method in java

Purpose : toString() method is overridden to get the String representation of the object.
If we directly print the object in java using System.out.print() it will give hashcode value as output. Lets see it with the help of an example

public class Emp {
       int empId;
       String empName;

       Emp(int id, String name){
              this.empId=id;
              this.empName=name;
       }

       public static void main(String[] args) {
              Emp e1 = new Emp(54110, "Mukesh");
              Emp e2 = new Emp(12243, "Rajnish");

              System.out.println(e1);
       }
}


OUTPUT :  Emp@3e25a5   
So what we get here is the hashcode value of the object. But we expected it to print the values contained by the object e1, something like this :
     54110, "Mukesh"
Isn't it?

How to overcome this problem?

override toString() method. Java compiler internally calls toString() so overriding this method will help us get the desired output as shown below 
public String toString(){
return xyz;
}

This time the above code override toString() :

public class Emp {
int empId;
String empName;

Emp(int id, String name){
this.empId=id;
this.empName=name;
}

public String toString(){                                                                        
return empId + " - "+ empName;                                                             
}                                                                                                                           

public static void main(String[] args) {
 Emp e1 = new Emp(54110, "Mukesh");
 Emp e2 = new Emp(12243, "Rajnish");
 
 System.out.println(e1);
 System.out.println(e2);

}


}

OUTPUT :
54110 - Mukesh

12243 - Rajnish

Now we get what we expected. This is the magic of overriding toString method. 

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.