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");
-
- System.out.println("Employee details: "+E1);
-
- System.out.println(E2+ " concatenation");
- }
- }
OutputEmployee details: Employee@13e8d89
Employee@9664a1 concatenation
In the preceding example, you can see that we couldn't get the desired output since E1 and E2 prints the class name, “@” and the hex version of the object's hashcode is concatenated to a string. The default hashcode method in the object is typically implemented by converting a memory address of an object to an integer.
This all happens due to the Java compiler calling the toString() method and by overriding it returns the specified value.
Example using toString() method
Now let's have a look at the example that uses the toString() method.
- 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 String toString()
- {
- return id+" "+name+" "+salary+" "+city;
- }
- public static void main(String args[])
- {
- Employee E1=new Employee(111,"Rakesh",50000,"Lucknow");
- Employee E2=new Employee(112,"Suresh",25000,"Kanpur");
-
- System.out.println("Employee details: "+E1);
- System.out.println("Employee details: "+E2);
- }
- }
OutputEmployee details: 111 Rakesh 50000 Lucknow
Employee details: 112 Suresh 25000 Kanpur
Here, by using the toString() method we are able to represent the object as a string without any hashcode concatenated to it.