toString() method in Java.
- toString() is a method of Object class. an Object is a superclass of every class in Java.
- toString() method returns the string representation of the object.
Sometimes we need to override toString() method. so the question is that why we need to override the toString() method in Java.
Let’s try to understand a real-time programming problem without overriding toString() method.
Here in below code, we are going to print object directly.
class Employee { private int emp_id; private String emp_name; public Employee(int emp_id, String emp_name) { super(); this.emp_id = emp_id; this.emp_name = emp_name; } } public class Main { public static void main(String[] args) { Employee emp = new Employee(101, "Golu"); System.out.println(emp); } }
Output: Employee@7852e922
So this output is a string representation of an object. its follow the proper format like “<fully qualified name of the class>@hexadecimal value of the object”.
overriding toString() method in Java.
class Employee { private int emp_id; private String emp_name; public Employee(int emp_id, String emp_name) { super(); this.emp_id = emp_id; this.emp_name = emp_name; } public String toString() { return emp_id+ " "+emp_name; } } public class Main { public static void main(String[] args) { Employee emp = new Employee(101, "Golu"); System.out.println(emp); } }
Output: 101 Golu.
Now you can see the right output which is exactly we need.