In Java, this method comes in handy when a user wants to represent any object as a string. It returns an object as a string.
The compiler of Java automatically invokes the toString() method on the object. Therefore, when the toString method is overridden, we get in return the desired output, which can be the state of an object as well depending on the implementation.
Example:
class Employee{
int id;
String name;
String city;
Employee(int id, String name, String city){
this.id=id;
this.name=name;
this.city=city;
}
public String toString()
{
return id+" "+name+" "+city;
}
public static void main(String args[])
{
Employee e1=new Employee(1001,"Vijay","Banglore");
Employee e2=new Employee(1002,"Deepak","Pune");
System.out.println(e1);
System.out.println(e2);
}
}