Home  >  Article  >  Java  >  How to use tostring method in java

How to use tostring method in java

anonymity
anonymityOriginal
2019-04-28 09:43:026999browse

We know that calling the object's toString() method will directly output the object's attribute information, but how is it implemented? And how to achieve it better? Now let’s learn.

How to use tostring method in java

We can know from the java documentation that the toString() method is defined in the Object class, and its return value type is String type, returning the class name and its reference address.

When connecting the String class to other types, the toString() method is automatically called. The demo is as follows:

Date now = new Date();
System.out.println("now = " + now);//相当于下一行代码
System.out.println("now = " + now.toString());

In actual applications, it can be rewritten in user-defined types as needed. toString() method, for example, the Stirng class overrides the toString() method and returns the value of the string. The dome is as follows

System.out.println(s1);//相当于下一行代码
System.out.println(s1.toString());

When the basic data type is converted to the String type, the toString() method of the corresponding packaging class is called. , the demo is as follows:

int a = 10;
System.out.println("a = " + a);

Now let’s see what the source code in jdk looks like:

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Now let’s practice using it:

Person p1 = new Person();
System.out.println(p1.toString());//TestEquals.Person@15db9742
System.out.println(p1);//TestEquals.Person@15db9742 因为输出的时候回默认调用Objec类toString()方法

When we print an object When referenced, the toString() method of this object is actually called by default

When the class of the printed object does not override the toString() method in Object, the toString() method in the Object class is called by default. .

Return the class where this object is located and the first address value of the corresponding heap space object entity.

When the class where we print the object overrides toString(), the overridden toString() method is called. Generally, the overriding is to return the attribute information of the class object.

We can also customize a tostring() method:

//手动实现
public String toString(){
return " Person:name=" + name +" age=" + age;
}

The above is the detailed content of How to use tostring method in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn