When you print an object using System,out.println (), the ToString method is called automatically

Source: Internet
Author: User

In Java, all objects are inherited from object, which naturally inherits the ToString method, which automatically calls the ToString method to print when using SYSTEM,OUT.PRINTLN () as a reference to an object. If the ToString method is overridden, the overridden ToString method is called.

Because this method of System.out.println () calls string.valueof (Objec O) in the source code,
public void println (Object x) {
String s = string.valueof (x);
Synchronized (this) {
print (s);
NewLine ();
}
}
And the source of string.valueof (x) is to call the object's ToString () method, the source code is as follows:
public static String valueOf (Object obj) {
return (obj = = null)? "Null": obj.tostring ();
}

For example, consider the difference between a string StringBuilder and a stringbuffer. The following use is StringBuilder).

Import Java.util.Random;


public class Usingstringbuilder {
public static random random = new random (47);
Public String toString () {
StringBuilder result = new StringBuilder ("[");
for (int i=0;i<25;i++) {
Result.append (Random.nextint (100));
Result.append (",");
}
Result.delete (Result.length ()-2, Result.length ());
Result.append ("]");
return result.tostring ();
}
public static void Main (string[] args) {
Usingstringbuilder u = new Usingstringbuilder ();
SYSTEM.OUT.PRINTLN (U);
}
}

Output result: [58,55,93,61,61,29,68,0,22,7,88,28,51,89,9,78,98,61,20,58,16,40,11,22,]

When you print an object using System,out.println (), the ToString method is called automatically

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.