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