Because it is a method already in object, and all classes inherit object, "All objects have this method".
It is usually just for the convenience of the output, such as System.out.println (XX), the parentheses inside the "XX" if it is not a string type, automatically call XX's ToString () method
All in all, it's just a way for the Sun company to develop Java in order to facilitate string manipulation of all classes.
Answer add:
The use of this method is to facilitate the operation, so in the file operation can not be used
Example 1:
public class ORC
{
public static Class A
{
Public String toString ()
{
Return "This is A";
}
}
public static void Main (string[] args)
{
A obj = new A ();
System.out.println (obj);
}
}
If a method has the following sentence:
A obj=new a ();
System.out.println (obj);
Will get output: this is A
Example 2:
public class ORC
{
public static Class A
{
Public String getString ()
{
Return "This is A";
}
}
public static void Main (string[] args)
{
A obj = new A ();
System.out.println (obj);
System.out.println (Obj.getstring ());
}
}
will get output: [email protected] class name plus address form
System.out.println (Obj.getstring ());
Will get output: this is A
See the difference, the advantage of ToString is that when encountering "println" such as the output method will be automatically called, do not explicitly hit out.
1 public class Zhang
3 {
5 public static void Main (string[] args)
7 {
9 StringBuffer MyStrBuff1 = new StringBuffer ();
mystrbuff1.append ("Hello, guys!");
System.out.println (mystrbuff1.tostring ());
Mystrbuff1.insert (6, 30);
System.out.println (mystrbuff1.tostring ());
+ }
21}
It is important to note that if you want to display stringbuffer on the screen, you must first call the ToString method to turn it into a string constant , because the PrintStream method println () Parameters of type StringBuffer are not accepted .
1 public class Zhang
2 {
3 public static void Main (string[] args)
4 {
5 String mystr = new StringBuffer ();
6 mystr = new StringBuffer (). Append (MyStr). Append ("guys!"). ToString ();
7 System.out.println (MYSTR);
8 }
3 ·
The ToString () method in this role is to convert the StringBuffer type to a string type.
1 public class Zhang
2 {
3 public static void Main (string[] args)
4 {
5 String mystr = new StringBuffer (). Append ("Hello"). toString ();
6 mystr = new StringBuffer (). Append (MyStr). Append ("guys!"). ToString ();
7 System.out.println (MYSTR);
8 }
3 ·
tostring Method in Java