How can the java tostring method be used?

In Java, the toString() method is a method provided by the Object class for returning the string representation of an object.

To use the toString() method, you can follow these steps:

  1. convert to a string
  2. Represent as a string
public class MyClass {
    private int number;
    private String text;
    
    // 构造方法等省略
    
    @Override
    public String toString() {
        return "MyClass [number=" + number + ", text=" + text + "]";
    }
}
  1. converts the object into a string representation
MyClass obj = new MyClass(123, "Hello");
System.out.println(obj.toString());

Or you can directly use the name of the object and the toString() method will be implicitly called.

MyClass obj = new MyClass(123, "Hello");
System.out.println(obj);

In this example, the rewritten toString() method returns a string representation containing the number and text properties. When the toString() method is called, it will return a string like MyClass [number=123, text=Hello].

It is important to note that the toString() method is inherited by all Java objects, so it can be used on any Java object. However, if the toString() method is not overridden, the default implementation will return the object’s hash code. To better display the object’s information, it is recommended to override the toString() method in the relevant class.

bannerAds