Wednesday, 16 March 2016

What is the problem if you try to print object you created in System.out.print();?

Note : Interviewer gave me the code snippet given below and asked the questions :
1. Will there be any problem if I print e1 as shown in code? 
2. If there is any problem then how will you solve it?
-----------------------------------------------------------------------------------------------------
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 name;
}

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. 


You may also like to read:



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.