Method of String in Java: toString () How to use

Source: Internet
Author: User
Tags stringbuffer

Tostring
public string toString () returns a string representation of the object. Typically, the ToString method returns a string that represents this object in text format. The result should be a concise but easy to read. It is recommended that all subclasses override this method.
The ToString method of the object class returns a string consisting of the class name (the object is an instance of the class), the at tag "@", and the unsigned hexadecimal representation of the object's hash code. In other words, the method returns a string whose value is equal to:

GetClass (). GetName () + ' @ ' + integer.tohexstring (hashcode ())

ToString is derived from the Java object class, defined in object as: Returns a string of class name @hashcode that can be overridden to return information that you think is useful,
tostrng not arguments
Override:public String toString () {
//Insert code return
"informations"
}
because in Java the object class is the base class, So each class will have a ToString method.
System.out.println (object) is actually the ToString method that invokes Object. The more
we use is the ToString method of the String class, which overrides the object's ToString method to return string values for string.
--------------------------------------------------------------------------------
Because it is the method that is already in object, all classes inherit object, so "all objects have this method"

It is usually only a convenient output of ginger, such as System.out.println (XX), parentheses inside (_kuo4 Hao4 li3 mian4) "XX" if not a string type, automatically invoke XX's ToString () method
All in all, it's just a way sun developed Java to make it easier for all classes of words (de0 shi2 hou4 wei4 le0 fang1 bian4) string operations to be added
ToString, try changing your name.
}
A obj=new a ();
System.out.println (obj);
Will get output: Xxxx@xxxxxxx class name plus address form
System.out.println (Obj.getstring ());
Will get output: this is A
The advantage of ToString is that it is automatically invoked when it encounters an output method such as "println", without explicitly typing

------------------------------------------------------------------------------------

Because it is a method that is already in object, all classes inherit object, so "all objects have this method."

It is usually just for the convenience of output, such as System.out.println (xx), "xx" in parentheses if it is not a string type, automatically calls the ToString () method of XX

All in all, it's just a way for sun to add to the convenience of all class string operations while Java is being developed

Answer added:

The purpose of writing this method is to facilitate operation, so it can be used in file operation.

Example 1:

public class a{

Public String toString () {return ' is A ';}

}

If a method contains the following sentences:

A obj=new a ();

System.out.println (obj);

Will get output: this is A

Example 2:

public class a{

Public String getString () {return ' this is A ';} ToString, try changing your name.

}

A obj=new a ();

System.out.println (obj);

Will get output: Xxxx@xxxxxxx 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 the "println" and so on when the output method will automatically call, do not explicitly typed out.

------------------------------------------------------------------------------------
ToString () is a method that overrides the parent object to express the object as a string.
General entity classes should override ToString (), Equals (), Hashcode (), and other method methods, such as user, student, and other entity classes
If a class is used to handle some business, there is no need to rewrite tostirng ()
These methods are encapsulated in the Commons-lang package,
1 public boolean equals (Object obj) {
Return Equalsbuilder.reflectionequals (this.obj);
}
2 public int hashcode () {
Return Hashcodebuilder.reflectionhashcode (this);
}
3 public String tostirng () {
Teturn tostringbuilder.reflectiontostring (this);
}

===========================================================================================

The ToString method of the object class returns a string consisting of the class name (the object is an instance of the class), the at tag "@", and the unsigned hexadecimal representation of the object's hash code. In other words, the method returns a string whose value is equal to:

GetClass (). GetName () + ' @ ' + integer.tohexstring (hashcode ())

For example: com.struts2.user@de6ced

When the ToString () method of the class is overridden, the return value of the ToString () method inside the class is returned.

View Plaincopy to Clipboardprint?
Package com.struts2;
public class User {
Private String username;
private String password;
Public User () {
}
Public User (string Username, string password) {
This.username=username;
this.password= password;
}

Public String GetUserName () {
return username;
}
public void Setusername (String username) {
This.username = Username;
}
Public String GetPassword () {
return password;
}
public void SetPassword (String password) {
This.password = password;
}

Public String toString () {
return This.username+this.password;
}
public static void Main (string[] args) {
System.out.println (New User ("John", "123456"));
}
}


The results are as follows: User name: John Password: 123456

------------------------------------------------------------------------------1. The ToString () Method object class has a ToString () method, and each class you create inherits the method. It returns a string representation of the object and is very helpful for debugging. However, the default ToString () method often does not meet the requirements, and needs to be overridden by this method.
The ToString () method

1. The ToString () Method object class has a ToString () method, and each class you create inherits the method. It returns a string representation of the object and is very helpful for debugging. However, the default ToString () method often does not meet the requirements, and needs to be overridden by this method.
The ToString () method converts an object to a string. Look at the following code:
Package sample;
Class Villain {
private String name;
protected void Set (String nm) {
name = NM;
}
Public villain (String name) {
THIS.name = name;
}
Public String toString () {
Return "I ' m a villain and my name is" + name;
}
}
public class Orc extends villain {
private int orcnumber;
Public ORC (String name, int orcnumber) {
Super (name);
This.orcnumber = Orcnumber;
}
public void Change (String name, int orcnumber) {
Set (name);
This.orcnumber = Orcnumber;
}
Public String toString () {
Return "ORC" + Orcnumber + ":" + super.tostring ();
}
public static void Main (string[] args) {
ORC ORC = new ORC ("Limburger", 12);
System.out.println (ORC);
Orc.change ("Bob", 19);
System.out.println (ORC);
}
}

Result:
Sample. Orc@11b86e7sample.orc@11b86e7
If you remove the annotation by adding 2 ToString () methods, you get
Result:
Orc12:i ' m a villain and my name is Limburgerorc19:i ' m a villain and my name is Bob
2. Use ToString ()
in the container class to write a tool class for outputting iterator in the console.
Import Java.util.Iterator;
public class Printer {
    static void printall (iterator e) {
    & Nbsp;  while (E.hasnext ()) {
            System.out.println (E.next ());
       }
    }
}

The

The ToString () method of the parent class is overridden in the Hamster class.
public class Hamster {
    private int hamsternumber;
    public Hamster (int hamsternumber) {
       this.hamsternumber=hamsternumber;
   &NBSP}
    public String toString () {
        return "This is hamster #" +hamsternumber;
    }
}

Use the container class in the Hamstermaze class to load the Hamster class object and output the results.
Import java.util.ArrayList;
Import java.util.List;
public class Hamstermaze {
@SuppressWarnings ("Unchecked")
public static void Main (string[] args) {
List list=new ArrayList ();
for (int i=0;i<3;i++)
List.add (New Hamster (i));
Printer.printall (List.iterator ());
}
}

Results:
This is hamster #0This are hamster #1This is hamster #2
3. A generic bean that implements ToString ()
When you work on a project, you find that many beans need to implement the ToString () method, implement a generic bean, and then inherit from the other.
Import Java.lang.reflect.Field;
public class Basebean {

Public String toString () {
StringBuffer sb = new StringBuffer ();
try {
Class t = This.getclass ();
field[] fields = T.getdeclaredfields ();
for (int i = 0; i < fields.length; i++) {
Field field = Fields[i];
Field.setaccessible (TRUE);
Sb.append ("{");
Sb.append (Field.getname ());
Sb.append (":");
if (field.gettype () = = Integer.class) {
Sb.append (Field.getint (this));
else if (field.gettype () = = Long.class) {
Sb.append (Field.getlong (this));
else if (field.gettype () = = Boolean.class) {
Sb.append (Field.getboolean (this));
else if (field.gettype () = = Char.class) {
Sb.append (Field.getchar (this));
else if (field.gettype () = = Double.class) {
          

Related Article

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.