Overriding toString() method in Java

In this tutorial, we will talk about overriding the toString() method in Java. This method belongs to the Object class. To know more about this, see this: toString() method in Java

Before we head further, let’s have a look at the below Java program.

class A{
    //a class
}

class Example {
  public static void main (String[] args) {
      A a = new A();
    System.out.println(a);
  }
}

Output:

A@232204a1

Now let us analyze the above program and the output.

In the above program, we have created a class A. In the main() method we create an object of this class and try to print it. As you can see in the output, It is printed in the following format: first, the class name followed by @ symbol and then hash code of the object.

We can override the toString() method to get the output in a format other than the predefined format.

Now, let’s say, we want to represent the object ‘a’ in a different way, we can do it by overriding toString() method. The following Java program demonstrates how we can override this method. Have a look at the program given here.

class A{
    //a class
    public String toString(){
        return "an object of class A." ;
    }
}

class Example {
  public static void main (String[] args) {
      A a1 = new A();
    System.out.println(a1);
    
    A a2 = new A();
    System.out.println(a2);
  }
}

Output:

an object of class A.
an object of class A.

In the above example, we have overridden the toString() method to get a string “an object of class A” whenever we print an object of class A.

Thank you.

Also read: StringBuffer class in Java

Leave a Reply