toString() Method in Java with Examples

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

The toString() method in Java provides a way to get a String representation of an object. This simple yet powerful method has become an indispensable tool for Java programmers.

In this article, we’ll understand the purpose of toString() and its advantages, see an example problem without it, and then use it in a complete code example.

The toString() method returns a String representation of the object it is called on. All classes in Java inherit this method from the Object class. The default implementation simply returns the class name and hashcode. However, we can override this method to customize the string representation as needed.

By providing a human-readable String version of an object, toString() allows easy printing and concatenation of object values. This helps debug and log application flow. Without toString(), trying to print object references results in useless hashcode values.

Advantages of Java’s toString()

Eliminates Need for Extensive Printing Code: One of the biggest advantages of toString() is that it removes the need to write multiple lines of code just to print values from different fields. We can simply override toString() and print all relevant class details automatically.

Customized Output: Since we are in full control of implementing toString(), we can customize the output in any format we want. Want JSON representation of an object? That is no problem; just format the string accordingly in toString().

Understanding the Problem Without toString()

Before using toString(), let’s first see a problem we face when printing objects directly:

public class Main {

  public static void main(String[] args) {
  
    Student john = new Student("John", 30, "Computer Science"); 
    Student mary = new Student("Mary", 25, "Business");
    
    System.out.println(john);
    System.out.println(mary);
  }

}

class Student {
  String name;
  int age;
  String major;
  
  Student(String name, int age, String major) {
    this.name = name;
    this.age = age; 
    this.major = major;
  }

}

This code creates two Student objects and tries to print them. Let’s see what the output looks like:

Student@5e265ba4
Student@1175e2db

We can see that printing objects directly results in some garbage hashcode values. This isn’t useful at all! We wanted to print each Student’s name, age and major.

This is where toString() comes to the rescue.

Example of Java’s toString() Method

class Student {

  String name;
  int age;
  String major;

  Student(String name, int age, String major) {
    this.name = name;
    this.age = age;
    this.major = major;
  }
  
  @Override
  public String toString() {
    return "Name: " + name + ", Age: " + age + ", Major: " + major; 
  }

  public static void main(String[] args) {
    Student student1 = new Student("John", 20, "Computer Science");
    Student student2 = new Student("Alice", 22, "Mathematics");

    System.out.println("Student 1: " + student1);
    System.out.println("Student 2: " + student2);
  }
}

Output:

Student 1: Name: John, Age: 20, Major: Computer Science
Student 2: Name: Alice, Age: 22, Major: Mathematics

Here, we’ve overridden the toString() method to return a String containing all the field values.

Conclusion

In conclusion, the Java toString() method is a crucial feature that provides a human-readable String representation of objects. It offers several advantages, including simplifying printing and concatenation of object details, eliminating the need for extensive custom printing code, and allowing customization of output formats.

Without toString(), object printing results in unhelpful hashcode values. By demonstrating its usage through an example, we can see how toString() improves the readability of object information, making it an invaluable tool for Java programmers.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

Leave a Reply

Your email address will not be published. Required fields are marked *