toString(); This method is used to convert any object in Java to String format. If we want to get object, Java Compiler automatically invokes 'toSting()' . Although we can override this method if required.
Lets Consider following example if we don't use this method.
package com.tech;
public class Employee {
private int Salary;
private String name;
public Employee(String name,int Salary) {
this.name=name;
this.Salary=Salary;
}
public static void main(String[] args)
{
Employee e1=new Employee("Ramesh",45000);
Employee e2=new Employee("Gaurav",25000);
System.out.println(e1); // compiler writes here e1.toString()
System.out.println(e2); //// compiler writes here e2.toString()
}
}
The Output we obtain is :
com.tech.Employee@20eb607d
com.tech.Employee@3d0bbf6d
But If we use toString() or Override this method like :
package com.tech;
public class Employee {
private int Salary;
private String name;
public Employee(String name,int Salary) {
this.name=name;
this.Salary=Salary;
}
public String toString(){return name+" "+Salary;} // over ride the toString()
public static void main(String[] args) {
Employee e1=new Employee("Ramesh",45000);
Employee e2=new Employee("Gaurav",25000);
System.out.println(e1);
System.out.println(e2);
}
}
Now we obtain the Output as:
Ramesh 45000
Gaurav 25000
0 Comment(s)