«Back to Home

Core Java

Topics

toString() Method In Java

toString()
 
The toString() method is used to return the string representation of the object.
 
When we want to print any object, Java compiler internally invokes the toString() method on the object. Hence, the toString() method overrides and returns the desired output. It can be the state of an object and it depends on our implementation.
 
Advantages of toString() method in Java
 
With overriding, the toString() method of the Object class, we can return the values of the object and we don't need to write much code. It saves time also.
 
Let’s see the problem without using toString() method in Java.
 
Code
  1. public class Bike {  
  2.     int bikeno;  
  3.     String bikename;  
  4.     Bike(int bikeno, String bikename) {  
  5.         this.bikeno = bikeno;  
  6.         this.bikename = bikename;  
  7.     }  
  8.     public static void main(String args[]) {  
  9.         Bike b1 = new Bike(1094"Pulsar");  
  10.         Bike b2 = new Bike(1169"Royal Enfield");  
  11.         System.out.println(b1);  
  12.         System.out.println(b2);  
  13.     }  
  14. }  
24

Output

25

In the example, shown above, we can see that b1 and b2 prints the hashcode values of the objects but we want to print the values of these objects. Java compiler internally invokes toString() method and overriding this method will return the particular values of the program.
 
Now, let's see the example of toString() method.
 
Code
  1. public class Bike {  
  2.     int bikeno;  
  3.     String bikename;  
  4.     Bike(int bikeno, String bikename) {  
  5.         this.bikeno = bikeno;  
  6.         this.bikename = bikename;  
  7.     }  
  8.     public String toString() { //overriding the toString() method    
  9.         return bikeno + " " + bikename;  
  10.     }  
  11.     public static void main(String args[]) {  
  12.         Bike b1 = new Bike(1094"Pulsar");  
  13.         Bike b2 = new Bike(1169"Royal Enfield");  
  14.         System.out.println(b1);  
  15.         System.out.println(b2);  
  16.     }  
  17. }  
26
 
Output

27

In the example, shown above, we can see that with overriding, the toString() method, we can get the desired output of the code due to which we use toString() method in Java.
 
Summary

Thus, we learnt that toString() method is used to return the string representation of the object in Java and also learnt their main advantages in Java.