SoFunction
Updated on 2025-04-17

Deep analysis and application scenarios of toString method in Java

1. Definition and function of toString method

toStringMethodThe official definition is the string representation of the return object. This sounds simple, but it does not matter. When we need to view the object's information in the form of a string, or output the object's information to logs, consoles, etc.toStringThe method comes in great use.

For example, we have onePersonClass, including name, age and other attributes. If we print this directlyPersonObject, not rewritetoStringMethod, then what you see will be a string of similarPerson@1a2b3cThe string, which is readable is simply zero. But if we rewrittentoStringMethod, let it returnName: Zhang San, Age: 20Such a string is obvious at a glance.

public class Person {
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Name: " + name + ", age: " + age;
    }
}

2. What should I pay attention to when rewriting the toString method?

(I) The integrity and simplicity of information

RewritetoStringWhen we do the method, we needMake sure the returned string contains important information about the object, but it cannot be too verbose. Let users quickly understand the key properties of objects.

For example, in an e-commerce systemOrderIn the class, we may only need to return key information such as order number and total price, without listing the detailed information of each product.

(II) Uniformity of format

To facilitate analysis and reading, try to maintain the uniform format. Fixed delimiters, such as commas, colons, etc., can be used to separate different attributes.

(III) Avoid performance problems

If there are many attributes of an object, or if some attributes are calculated,RewritingtoStringPay attention to avoid performance issues when doing the method. Consider including only necessary properties, or optimizing time-consuming calculations.

(IV) Thread safety

ifObjects may be accessed in a multi-threaded environment, then rewritetoStringThread safety issues should be considered when doing the method. For example, you can use synchronization mechanisms or avoidtoStringModify the state of the object in the method.

(V) Avoid recursive loops

This is a relatively easy issue to be overlooked. If the object's properties contain other objects, and these objects refer to the current object, then rewritetoStringMethods may lead to recursive loops, which will eventually lead to stack overflow errors.

For example,

We have oneAClass and oneBkind,AThere is one in the classBAttributes of types,BThere is another one in the categoryAAttributes of types.

If we areAClassictoStringThe method is calledBClassictoStringmethod,

And inBClassictoStringThe method is called againAClassictoStringMethods, then you will fall into a dead loop of infinite recursion.

To avoid this, we cantoStringRestrict recursive calls in the method, such as using a tag to record whether it has been called.toStringMethod, or only print part of the information of the object.

public class A {
    private B b;

    @Override
    public String toString() {
        if (b == null) {
            return "A@null";
        }
        return "A@" + ();
    }
}

public class B {
    private A a;

    @Override
    public String toString() {
        if (a == null) {
            return "B@null";
        }
        return "B@" + ();
    }
}

In this example, if we createAandBObjects, and let them refer to each other, then invokeAThe object'stoStringMethods will lead to recursive loops.

To avoid this problem, we cantoStringAdd a tag to the method, such as:

public class A {
    private B b;
    private boolean isToStringCalled = false;

    @Override
    public String toString() {
        if (isToStringCalled) {
            return "A@...";
        }
        isToStringCalled = true;
        if (b == null) {
            return "A@null";
        }
        return "A@" + ();
    }
}

public class B {
    private A a;
    private boolean isToStringCalled = false;

    @Override
    public String toString() {
        if (isToStringCalled) {
            return "B@...";
        }
        isToStringCalled = true;
        if (a == null) {
            return "B@null";
        }
        return "B@" + ();
    }
}

In this way, whentoStringWhen the method is called, if it is found that the tag has been set totrue, returns a simplified string, avoiding recursive loops. (This comparison is similar to avoiding mutex mutex locks)

3. How to call the toString method of the parent class in a custom class?

Sometimes, we rewrittentoStringMethod, but also hope to retain the parent classtoStringMethod information.

At this time, you can use it()To call the parent classtoStringmethod.

For example, we have oneStudentClass inherits fromPersonkind,StudentThe student number attribute has been added to the class.

RewritingStudentClassictoStringWhen a method, we can first call the parent class’stoStringMethod, and then add the information of the student number.

public class Student extends Person {
    private String studentId;

    @Override
    public String toString() {
        return () + ", Student ID: " + studentId;
    }
}

In this way, when we print aStudentWhen using an object, you can see information about the parent class and the child class at the same time.

4. In addition to the Object class, what are the toString methods of the classes are more commonly used?

(I) Collection Class

Collections such asArrayListHashMapWait, theirtoStringThe method returns a string representation of elements in the collection. This is very convenient when debugging and viewing collection content.

ArrayList<String> list = new ArrayList<>();
("a");
("b");
("c");
(());  // Output: [a, b, c]

(II) Date category

Date categories such asDateLocalDateWait, theirtoStringThe method returns a string representation of the date.

Date date = new Date();
(());  // The output is similar: Fri Apr 05 10:30:45 GMT 2024
LocalDate localDate = ();
(());  // The output is similar: 2024-04-05

(III) Numerical packaging

Numerical packaging categories such asIntegerDoubleWait, theirtoStringThe method returns a string representation of the numeric value.

Integer num = 123;
(());  // Output: 123
Double d = 3.14;
(());  // Output: 3.14

5. Application scenarios of toString method

(I) Debugging

During the debugging process,toStringMethods can help us quickly view the status of objects. For example, in the IDE debugger, when we look at an object, the debugger will usually call the object'stoStringMethod to display object information.

(II) Logging

In logging, we often need to record the information of the object as a string. At this time,toStringThe method comes in great use.

Logger logger = ();
Person person = new Person("Zhang San", 20);
(());

(III) User interface display

In the user interface, sometimes it is necessary to display the object information to the user as a string. For example, displaying the user's personal information in a table, you can use ittoStringMethod to get the string representation of the user object.

6. Summary

toStringAlthough the method seems simple, it has a wide range of applications in Java programming. RewritetoStringWhen doing the method, pay attention to the integrity, simplicity, uniformity of the format, and avoiding performance problems and recursive loops. In a custom class, you can use()To call the parent classtoStringMethod to retain information of the parent class. Apart fromObjectIn addition to the class, collection class, date class, numerical packaging class, etc.toStringThe method is also commonly used. I hope this blog can help you better understand and use ittoStringMethod, go further and further on the road of Java programming!

This is the article about the in-depth analysis and application scenarios of the toString method in Java. For more detailed explanations of the Java toString method, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!