Introduction
In this article, we will learn about one of the important methods, the toString() method, in Java with a basic illustration for a better understanding and explanation.
About toString() method
Basically it is a method that is used when we need a string representation of the object. It is defined in the object class. This method returns the string representation of the object.
The implementation of toString() method can be done by overriding the object's toString method. This method can be overridden to customize the string representation of the object.
When we print an object, the Java compiler internally invokes the toString() method and overrides it for the desired output.
Example without using toString() method
Let's see the example without using the toString() method and analyse the problem that occurs.
- class Employee
- {
- int id,salary;
- String name;
- String city;
- Employee(int id, String name, int salary ,String city)
- {
- this.id=id;
- this.name=name;
- this.salary=salary;
- this.city=city;
- }
- public static void main(String args[])
- {
- Employee E1=new Employee(111,"Rakesh",50000,"Lucknow");
- Employee E2=new Employee(112,"Suresh",25000,"Kanpur");
- // using the default Object.toString method
- System.out.println("Employee details: "+E1);
- // implicitly calls the toString() method on object as a part of string concatenation
- System.out.println(E2+ " concatenation");
- }
- }

Gowtham RajamanickamPosted May 19, 2015, 12:50 AM
good one