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
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
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;
}
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:
- StringBuffer vs StringBuilder
- can a constructor be declared as final?
- benefits of having non-final class
- ArrayList vs Array
- checked exception vs unchecked exception
No comments:
Post a Comment