Java toString Method

Implementing toString method in java is done by overriding the Object’s toString method. The java toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object. Below is a program showing the use of the Object’s Default toString java method.
 class PointCoordnate {  
      private int a, b;  
      public PointCoordnate(int a, int b) {  
           this.a = a;  
           this.b = b;  
      }  
      public int geta() {  
           return a;  
      }  
      public int getb() {  
           return b;  
      }  
 }  
 public class JavaToString {  
      public static void main(String args[]) {  
           PointCoordnate point = new PointCoordnate(20, 20);  
           // using the Default Object.toString() Method  
           System.out.println("Object toString() method : " + point);  
           // implicitly call toString() on object as part of string concatenation  
           String s1 = point + " TEST";  
           System.out.println(s1);  
      }  
 }  

When you run the JavaToString program,
the output is:
Object toString() method : PointCoordnate@119c082
PointCoordnate@119c082 TESTING

In the above example when we try printing PointCoordinate object, it internally calls the Object’s toString() method as we have not overridden the java toString() method. Since out example has no toString method, the default one in Object is used. The format of the default toString method of the Object is as shown below.
Class Name, “@”, and the hex version of the object’s hashcode concatenated into a string. The default hashCode method in Object is typically implemented by converting the memory address of the object into an integer.

getClass().getName() + '@' + Integer.toHexString(hashCode());
Below is an example shown of the same program by Overriding the default Object toString() method. The toString() method must be descriptive and should generally cover all the contents of the object.
 class PointCoordnate {  
      private int a, b;  
      public PointCoordnate(int a, int b) {  
           this.a = a;  
           this.b = b;  
      }  
      public int geta() {  
           return a;  
      }  
      public int getb() {  
           return b;  
      }  
      public String toString() {  
           return "a=" + a + " " + "b=" + b;  
      }  
 }  
 public class JavaToString {  
      public static void main(String args[]) {  
           PointCoordnate point = new PointCoordnate(20, 20);  
           System.out.println("Object toString() method : " + point);            
           String s1 = point + " TESTING";  
           System.out.println(s1);  
      }  
 }  
When you run the JavaToString program,
the output is: a=20 b=20 a=20 b=20 TESTING