The toString() method

java.lang.Object is having a toString() method.It gives the string representation of an object . Te default implementation gives the class name and hash code number seperated by @. Let us see an example.

public class Employee {
private int id;
private String name;
public Employee(int number, String name) {
this.id = number;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
Employee employee = new Employee(1, "Bijoy");
System.out.println("String representation = " + employee.toString());
}
}

Now let us see the output

Output

String representation = com.object.Employee@4a6ca1a6

So the default implementation does not give a meaningful representation.To get a meaningful representation , we need to override the toString() in our class.Let us see an example.

public class Employee {
private int id;
private String name;
public Employee(int number, String name) {
this.id = number;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return new String("Id : "+getId() +" ; Name : "+getName());
}
public static void main(String[] args) {
Employee employee = new Employee(1, "Bijoy");
System.out.println("String representation = " + employee.toString());
}
}

Here we overrode the toString()  method to get a meaningful string representation.Now let us see the output.

Output

String representation = Id : 1 ; Name : Bijoy

So whenever we need a meaningful representation of  particular object , we should override the toString() method.