Java Object Class toString() Method

The java.lang.Object.toString() method is used to retrieve object information in string form. The prototype of toString() method in Object class in Java is:- public String toString()

Every class is having its own class name, hashcode, and state. In java.lang.Object class toString() method is implemented for returning the class name and hashcode of the current object in the hexadecimal format as [email protected] It is internally calling getClass() method and hashCode() method. The toString method implementation logic given in the Object class as shown below:

public String toString() {
  return getClass().getName() + "@" 
         + Integer.toHexString(hashCode());
}

Let us demonstrate it through an example,

public class Test {
   public static void main(String[] args) {
      Test t1 = new Test();
      System.out.println(t1);
      System.out.println(t1.toString());

      Test t2 = new Test();
      System.out.println(t2);
   }
}

Output:-

[email protected]
[email protected]
[email protected]

Whenever we are trying to print an Object reference then internally toString() method will be called. Since the toString() method is not defined in the Test class, so the compiler will search for it in the superclass. Directly or indirectly every Java class is a subclass of java.lang.Object class. Therefore, the toString() method will be executed from the Object class and display the string “[email protected]”. Another example:-

class Student {
   private int id;
   private String name;

   // constructor
   Student(int id, String name) {
      this.id = id;
      this.name = name;
   }
}

public class Test {
   public static void main(String[] args) {
      Student s1 = new Student(100, "Emma");
      System.out.println(s1);

      Student s2 = new Student(101, "Noah");
      System.out.println(s2);
   }
}

Output:-

[email protected]
[email protected]

Override toString() in Java

The above outputs are not meaningful messages. It should display Student object data, rather than its references. If we want to return the object’s state from this method we must override it in the subclass. Based on our requirement we can override the toString() method in our class to provide our own representation.

public class Test {

   @Override
   public String toString() {
      return "Test";
   }

   public static void main(String[] args) {
      Test t1 = new Test();
      System.out.println(t1);
      System.out.println(t1.toString());

      Test t2 = new Test();
      System.out.println(t2);
   }
}

Output:-

Test
Test
Test

Now, in the Test class toString() method is overriden and returing “test” string. Therefore whenever we try to print object reference then it is executed from Test class and returns “test” String. Let us see another example:-

class Student {

   private int id;
   private String name;

   // constructor
   Student(int id, String name) {
      this.id = id;
      this.name = name;
   }

   // overriding toString() method
   @Override
   public String toString() {
      return id + " " + name;
   }
}

public class Test {
   public static void main(String[] args) {
      Student s1 = new Student(100, "Emma");
      System.out.println(s1);

      Student s2 = new Student(101, "Noah");
      System.out.println(s2);
   }
}

Output:-

100 Emma
101 Noah

In the Student class toString() method is overridden and returning state or data of the object. Therefore whenever we are trying to print an object reference then it will display the id and name of the Student object.

Use of toString Method in Java

In all wrapper classes, all collection classes, Arrays class, String class, StringBuffer class, and StringBuilder class the toString() method is overridden. That’s we are getting object data rather than its reference.

import java.util.ArrayList;
import java.util.Arrays;
public class Test {
   public static void main(String[] args) {

      // String class 
      String s = "KnowProgram";
      System.out.println(s);

      // Wrapper classes
      Integer io = Integer.valueOf(10);
      System.out.println(io);
      Double d = Double.valueOf(19.5);
      System.out.println(d);

      // ArrayList class
      ArrayList<Character> al = new ArrayList<Character>();
      al.add('K');
      al.add('P');
      System.out.println(al);

      // array 
      int arr[] = new int[]{1, 2, 3, 4, 5};
      System.out.println(Arrays.toString(arr));
   }
}

Output:-

KnowProgram
10
19.5
[K, P]
[1, 2, 3, 4, 5]

Relation between toString() and hashCode() methods

When toString() method is not overrridden in the class then the toString() method is executed from the Object class. Object class toString() method internally called hashCode() method.

But if we are overriding the toString() method then it may or may not call hashCode(), it completely depends on the implementation logic.

#Case1:- Both toString() and hashCode() methods are not overriden.

class A{

  int x;

  A(int x){
    this.x = x;
  }
}

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

Output:-

[email protected]

Here toString() and hashCode() methods are executed from Object class and returns [email protected] hashCodeInHexadecimalFormat

#Case2:- Only hashCode() method is overriden.

class A{

  int x;

  A(int x){
    this.x = x;
  }

  @Override
  public int hashCode(){
    return 9;
  }
}

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

Output:-

[email protected]

Whenever we try to print object reference then the toString() method is called. Since toString() is not overridden in the A-class so it will be called from the Object class. The toString() of Object class internally called hashCode() method, but the hashCode method is overridden in class A. So, the hashCode() method will be executed from the A-class and displayed [email protected]

#Case3:- The hashCode() and toString() method, both are overriden.

class A{

  int x;

  A(int x){
    this.x = x;
  }

  @Override
  public int hashCode(){
    return 9;
  }

  @Override
  public String toString() {
    return "" + x;
  }
}

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

Output:-

18

Since toString() method is overriden and its implementation logic is not calling any other methods, directly returning value in string format. Hence hashCode() method won’t get any chance to execute.

#Case4:- Only toString() is overriden.

It is similar to the previous case. When toString() is overridden then it may or may not call hashCode(), it depends on its implementation logic.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply