JAVA tostring Method

Source: Internet
Author: User
Tags ming

In Java, all objects have the ToString method;

The ToString method is not defined when the class is created, and the hash value of the object is output when the object is output;

It's just a way for the Sun company to develop Java in order to facilitate string manipulation of all classes.

It is usually just for ease of output:

For example:

 Public classtest2{String name; intAge ;  PublicString toString () {return"My name is:" +name+ "\ t my age is:" +Age ; }     Public Static voidMain (string[] args) {Test2 Myclass=NewTest2 (); Myclass.name= "Xiao Ming"; Myclass.age= 20;    System.out.println (Myclass); //call the object's ToString method by default when using the object name directlySystem.out.println (Myclass.tostring ());//To call the string method manually    }}

Operation Result:

If the ToString method is not defined in the class, the hash value of the object is output when the above case is called, as shown in the following case:

 Public classtest2{String name; intAge ; /*Public String toString () {return "My name is:" +name+ "\ t my age is:" +age; }*/     Public Static voidMain (string[] args) {Test2 Myclass=NewTest2 (); Myclass.name= "Xiao Ming"; Myclass.age= 20;    System.out.println (Myclass); //call the object's ToString method by default when using the object name directlySystem.out.println (Myclass.tostring ());//call the string method manually even if the ToString method is not defined, it can be called because all objects have the ToString method by default    }}

Operation Result:

JAVA tostring Method

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.