Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

toString Method in Java

Java provides several in-built methods to perform various operations. The toString method in Java is one such method that is used to convert an object into a string representation. This article will go through the toString method in Java, its default implementation, and how to override the toString method in Java. In the end, this article will also discuss the advantages of using toString method in Java.

What is the toString Method in Java?

The toString method in Java is an in-built method that returns a string representation of an object. This method is defined in the Object class which is the root class for all Java classes, and most classes in Java override this method to provide a meaningful string representation of the object.

The toString method in Java is used for a variety of purposes, including debugging, logging, and displaying an object’s status. It is frequently used to collect information about an object and its current state.

By default, the toString method in Java returns a string that contains the class name, the "@" symbol, and the object’s hash code in hexadecimal format. This string representation is not always meaningful or useful for the programmer, and therefore the toString() method is often overridden to provide a more meaningful string representation of the object.

For example, consider a Person class with properties such as name, age, and address. By overriding the toString() method, we can obtain a string representation of the Person object that contains these properties, making it easier to obtain information about the object’s state.

Default Implementation of toString Method in Java

The default implementation of toString method in java returns a String consisting of the class name followed by an "@" sign and the hexadecimal representation of the object’s hash code.

Here’s an example of the default implementation of the toString method in Java:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Main {
    public static void main(String [] args){
        Person person = new Person("PrepBuddy", 30);
        System.out.println(person.toString());
    }
}

Output:

Person@5caf905d

Explanation: In the above example, the default implementation of toString() returns the class name (Person) followed by an "@" sign and the hexadecimal representation of the object’s hash code (5caf905d).

How to Override the toString Method in Java?

In Java, you can provide a customized string representation of an object by overriding the toString() method. This is helpful when printing the contents of an object in a human-readable format or logging information about the item.

To override the toString() method, you need to add the method to your class and provide your own implementation. The toString method must return a String that represents the object.

Here’s an example of how to override the toString method in Java:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class Main {
    public static void main(String [] args){
        Person person = new Person("PrepBuddy", 25);
        System.out.println(person.toString());
    }
}

Output:

Person{name='PrepBuddy', age=25}

Explanation: In the above example, the toString() method now returns a string that includes the name and age of the person, which is much more useful than the default implementation which we discussed earlier.

Java Classes with Overridden toString() Method

In Java, not all classes have the toString() method overridden by default. However, some of the commonly used classes that have the toString() method overridden by default are:

Let’s look at some Java classes that have implemented the toString() method to provide a meaningful string representation of the objects.

In Java, the toString() method is overridden by all wrapper classes such as Byte, Integer, Long, Float, Double, Boolean, and Character. String, StringBuilder, and StringBuffer have also overridden the toString() method.

Let’s take an example to understand it more clearly

import java.util.*;

public class Main {

  public static void main(String[] args) {
    Integer integer = 25;
    String name = "PrepBuddy";

    List<String> students = new ArrayList<>();
    students.add("Himanshu");
    students.add("Ankit");
    students.add("Deepak");

    System.out.println(integer);
    System.out.println(name);
    System.out.println(students);
  }
}

Output:

25
PrepBuddy
[Himanshu, Ankit, Deepak]

Explanation: In the above example, there are two things that stand out. First, we did not use the toString() method to print the string value of objects because by default System.out.println() uses the toString() method internally. Second, we did not implement the toString() method, instead, java itself override it for us.

Advantages of Using toString Method in Java

The toString method in Java has several advantages:

  • The toString method in Java provides a human-readable representation of an object. This is useful when we need to log or print the contents of an object.
  • The toString() method is often used to help in debugging. By providing a customized string representation of an object, you can quickly identify the state of the object and any potential issues.
  • The toString method in Java is simple to implement and requires only a few lines of code.
  • Many Java APIs, such as logging frameworks and serialization, rely on the toString() method to provide a string representation of an object. By implementing toString() method, your code can interact more easily with these APIs.
  • By providing a customized string representation of an object, the code becomes more readable and easier to understand for other developers.

Conclusion
In conclusion, the toString method in Java is a built-in method that is defined in the Object class and returns a string representation of an object. It is declared in the Object class and is commonly overridden in Java classes in order to provide a more relevant and useful string representation of the object. If a class does not override the toString() method, the default implementation provided by the Object class is used. However, by overriding this method, you can provide a customized string representation of an object that is more useful for logging, debugging, and improving code readability.

FAQs

Here are some frequently asked questions related to the toString method in java.

Q1: What is the role of the toString method in Java?
Ans: The toString() method is used to obtain a string representation of an object in Java. It is often used in debugging, logging, or printing the state of an object.

Q2: Can I override the toString() method to return null?
Ans: Yes, you can override the toString() method to return null. However, this is generally not recommended as it can cause issues with other Java APIs that rely on the toString() method.

Q3: What is the return type of the toString method in Java?
Ans: The return type of the toString() method in Java is String.

Q4: Is the toString() method defined in all Java classes?
Ans: Yes, the toString() method is defined in the Object class, which is the root class for all Java classes. Therefore, any Java class can inherit the toString() method from the Object class.

Q5: Can I use the toString() method to compare two objects?
Ans: No, you should not use the toString() method to compare two objects. The toString() method is used to provide a string representation of an object, and the string may not be unique for each object. Instead, you should use the equals() method to compare two objects.

Leave a Reply

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