View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

toString() Method in Java: Syntax, Usage & Examples

Updated on 24/06/202512,806 Views

Why does printing an object in Java often return unreadable text like ClassName@1a2b3c4—and how can you fix it?
This is where the toString() method in Java plays a key role. It’s defined in the Object class and returns a string that represents the object. By default, this string includes the class name and memory reference. But when overridden, toString() can display detailed, readable object data, making debugging and logging much easier.

In this tutorial, you’ll explore the functionality of the toString() method in Java, its syntax, return value, and real-world use cases. You’ll also learn how to override it correctly, use it with arrays and exceptions, and understand what happens when you don’t override it in custom classes.

Looking to sharpen your Java and OOP skills for real-world development? Explore upGrad’s Software Engineering Courses to learn Java, object-oriented programming, and system design with hands-on projects.

What is the toString() Method in Java?

The toString() method in Java is a pre-defined method in the Object class. It serves as the base class for all Java classes. It is used to retrieve a string representation of an object.

Nevertheless, developers can override this method in their own classes to provide a customized string representation. This allows for tailored object representations, facilitating debugging, logging, and displaying object information. Moreover, the toString() method is extensively employed in Java APIs and frameworks for converting objects to strings for various purposes.

Functionality and Return Values of toString() method

The toString() method in Java obtains a string representation of an object. It returns a string that represents the object's state or contents. Its default implementation returns a string representation that includes the class name, an ‘@‘ symbol, and the object's memory address.

toString() Method in Java Syntax

Here is the syntax for the toString() method:

@Override
public String toString() {
    // Generate the string representation of the object
    // Return the generated string
}

To override the toString() method in a class, you must include the @Override annotation to ensure that you correctly override the method from the superclass. Within the method body, you generate the string representation of the object based on its state and return the generated string.

How to use the toString() in Java

Here's an example of how to use the toString() method:

In the above example, the Person class overrides the toString() method to provide a string representation of a Person object. The toString() method returns a string that includes the name and age of the person.

When the toString() method is called on a Person object, it returns the generated string representation, which is then printed using System.out.println() in the main() method.

Code:

public 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 static void main(String[] args) {
        Person person = new Person("John Doe", 25);
        System.out.println(person.toString());
    }
}

Advantage of Java toString() Method

The Java toString() method offers several benefits:

  • Simplified object representation: The toString() method provides a convenient way to obtain a string representation of an object, making it easier to access and display object information without directly accessing its properties.
  • Debugging and logging support: By overriding the toString() method, developers can include relevant object details in the string representation, aiding in debugging and identifying runtime issues. It also facilitates logging objects in a readable format.
  • Improved readability: Customizing the toString() method allows developers to create more meaningful and readable output when printing or displaying objects, presenting information concisely and understandably.
  • Integration with Java APIs: Many Java APIs and frameworks rely on the toString() method, as standard Java classes often override it to provide useful string representations. This enhances interoperability with various Java libraries, APIs, and tools.
  • Customization and flexibility: Developers can tailor the toString() method to define their own object string representation, choosing which properties or information to include. This enables customization based on specific requirements.

Understanding the Problem With Not Overriding the toString() Method

When the toString() method in Java is not overridden, the default implementation provided by the Object class is utilized. However, relying on the default toString() method can be problematic as it may not offer a clear understanding of the object's state or contents. This can pose challenges when attempting to debug or log information about the object during runtime.

Furthermore, in scenarios where APIs or frameworks rely on the toString() method, the lack of a customized implementation can result in less useful output. This can hinder the interpretation and utilization of objects within these contexts.

To address these issues, it is recommended to override the toString() method in Java classes and provide a customized implementation that provides a more meaningful representation of the object's state. This facilitates easier debugging, logging, and integration with other Java components.

toString() method in Java example

In this example, the Book class represents a book with a title, author, and publication year. The toString() method is overridden to provide a custom string representation of the Book object. It generates a string that includes the title, author, and year.

In the main method, a Book object named book is created with the title "The Great Gatsby", author "F. Scott Fitzgerald", and year 1925. The toString() method is then called on the book object, and the resulting string representation is printed using System.out.println().

Code:

public class Book {
    private String title;
    private String author;
    private int year;
    public Book(String title, String author, int year) {
        this.title = title;
        this.author = author;
        this.year = year;
    }
    @Override
    public String toString() {
        return "Book{" +
                "title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", year=" + year +
                '}';
    }
    public static void main(String[] args) {
        Book book = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);
        System.out.println(book.toString());
    }
}

toString() Method in Java Array

In this example, the toString() method is invoked on an array of integers (numbers). By default, the toString() method inherited from the Object class is called, which returns a string representation of the array's memory address.

public class upGradTutorials {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        System.out.println(numbers.toString());
    }
}

The above code declares an array of integers named numbers and initializes it with values. The toString() method is then invoked on the numbers array. By default, the toString() method inherited from the Object class is called, which returns a string representation of the array's memory address. The result is printed using System.out.println().

toString() Method in Java Exception

In this example, the toString() method is invoked on an ArithmeticException object, which is thrown when dividing by zero. The toString() method provides information about the exception, including the exception class name and a message.

public class upGradTutorials {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println(e.toString());
        }
    }
}

The code demonstrates exception handling for an arithmetic operation that causes a divide-by-zero error. An arithmetic operation is performed inside a try-catch block where 10 is divided by 0. This operation throws an ArithmeticException.

The exception is caught using a catch block that specifies ArithmeticException. Inside the catch block, the toString() method is called on the exception object (e) to get a string representation of the exception. The resulting string, which contains the exception class name and a message, is printed.

Override toString() Java

In this example, the toString() method is overridden in the Vehicle class to provide a custom string representation of the object. The method returns a string that includes the vehicle's make, model, and year.

public class Vehicle {
    private String make;
    private String model;
    private int year;
    public Vehicle(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }
    @Override
    public String toString() {
        return "Vehicle{" +
                "make='" + make + '\'' +
                ", model='" + model + '\'' +
                ", year=" + year +
                '}';
    }
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle("Toyota", "Camry", 2022);
        System.out.println(vehicle.toString());
    }
}

The above example defines a class named Vehicle with private variables make, model, and year. The class has a constructor to initialize these variables. The toString() method is overridden with a custom implementation that returns a string representation of the object. The method concatenates the values of make, model, and year with additional text for clarity.

In the main() method, a Vehicle object is created and assigned values. The toString() method is called on the object, and the resulting string representation is printed.

Conclusion

Understanding the toString() method in Java is crucial for obtaining a meaningful string representation of objects. By customizing the toString() method, developers can enhance their Java applications' debugging, logging, and integration capabilities.

Enrolling in a course from upGrad can be highly beneficial for a comprehensive understanding of Java and its various features, including the toString() method. upGrad offers industry-relevant courses taught by experienced instructors, providing a structured learning path and hands-on projects to strengthen your Java skills.

FAQs

1. What is the toString() method in Java?

The toString() method in Java is used to convert an object into a readable String format. It’s defined in the Object class and is automatically available in every Java class unless overridden for custom output.

2. Why should you override the toString() method in Java?

Overriding the toString() method in Java lets you control how object data is represented as a string. This is useful for logging, debugging, and displaying meaningful information when printing objects in the console.

3. What does the default toString() method return?

By default, the toString() method in Java returns a string in the format ClassName@hashcode, which isn’t human-readable. This is why overriding it is recommended for custom classes and domain objects.

4. How do you override the toString() method in Java?

To override the toString() method in Java, you define it inside your class and return a custom string format that describes the object’s fields or properties. This helps in presenting meaningful outputs when the object is printed.

5. What is the syntax of the toString() method in Java?

The typical syntax is:

javaCopyEditpublic String toString() {
return "custom string representation";
}

This method must return a string and should be placed inside your Java class when you want to override the default behavior.

6. What happens if you don’t override toString() in Java?

If you don’t override toString(), printing an object will return a default string with class name and memory hashcode, which lacks useful information and isn’t helpful for debugging or user-facing output.

7. Can you use the toString() method in Java arrays?

Directly printing an array using toString() won’t give expected results. Instead, use Arrays.toString(array) for one-dimensional arrays and Arrays.deepToString() for multidimensional arrays to get a proper string representation.

8. How does toString() help with Java exceptions?

The toString() method in Java exceptions returns the class name and the error message. It’s commonly used in logs or debugging to understand the type and context of exceptions thrown during execution.

9. Is toString() automatically called in Java?

Yes. When an object is passed to System.out.println() or string concatenation, Java automatically calls the toString() method to convert the object into a string. If not overridden, the default version is used.

10. How is toString() different from valueOf() in Java?

Both toString() and valueOf() return string representations, but valueOf() is often used for converting primitive types and objects into strings using static methods like String.valueOf(). toString() is more commonly overridden in custom classes.

11. When should you avoid overriding toString() in Java?

Avoid overriding toString() in Java if your class doesn’t require a human-readable representation or isn’t intended to be logged or printed. Also, be cautious not to expose sensitive data while formatting the output.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.