Research and use of toString () method in Java, javatostring
Research and use of toString () method in Java
All classes indirectly or directly inherit objects, so each class has toString () and equals () methods. Here we only discuss toString ();
Usage:
①1. toString () indicates the name combination (meaning of conversion string type). 2. It is used in the print output statement,
②Generally, you need to output useful information.
③In addition, he is a method specially added by sun when developing Java to facilitate string operations of all classes.
Java's own two forms of general toString () return values
Return Value of toString () method:
①Public String toString (){
Return getClass (). getName () + "@" + Integer. toHexString (hashCode ());
} (Not overwritten)
②Public String toString (){
Return this;
} (Rewritten)
Use the Println () method with toString:
If the parameters in the Println () method are not (display call), call the toString () method,
As long as it is a reference type except the String type, basic type form (int char ),
Besides the reference array type of the basic type (char [] int [], etc.), toString () is called by default in the Println () method ();
①Public void println (Object x ){
// Return and call the toString () method to print the string Information
String s = String. valueOf (x );
Synchronized (this ){
Print (s); // print
NewLine (); // line feed
}
}
Public static String valueOf (Object obj ){
Return (obj = null )? "Null": obj. toString ();
}
②Public void println (String x ){
Synchronized (this ){
Print (x); // print
NewLine (); // line feed
}
}
③Public void println (char x ){
Synchronized (this ){
Print (x );
NewLine ();
}
}
④Public void println (char x []) {
Synchronized (this ){
Print (x );
NewLine ();
}
}
Many basic data types are not listed one by one as the println parameter.
Public class Address {public static void main (String [] args) {// basic data type println ④, print the output char [] d = new char [] {'A', 3,4}; System. out. println (d); // reference data type println ④. Call toString () String [] aa = new String [] {"1", "2"}; System. out. println (aa); // String type, directly print the output return thisString bb = new String ("bb"); System. out. println (bb); // The array type of the basic data type references println ④ type, directly print the output char [] ch = new char [] {'1', '2 '}; system. out. println (ch); // object type Object ob = new Object (); System. out. println (ob); // toString () converts a String of the stringBuffer type into a String of the StringBuffer str = new StringBuffer ("1234"); String str2 = str. toString (); System. out. println (str );}}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger. Http://blog.csdn.net/bestxianfeng163/article/details/76545807