Issue 2 Comparison of the String class equals and "= ="

Source: Internet
Author: User

the "= =" comparison is the same object, that is, whether the memory address is the same

"equals in String" compares the contents of an object

"equals in Object" is equivalent to "=" if not overridden by the Equals method, and if you are comparing object content, you must override the Equals method, because most of the actual applications are comparisons of object content. (See also question 1)

1string S1 = "string";2String s2 = "string";3String s3 =NewString ("string");4String S4 =NewString ("string");5System.out.println (S1 = = s2);//result is true6System.out.println (S1 = = S3);//The result is false7System.out.println (s1.equals (S2));//result is true8System.out.println (S1.equals (S3));//result is true9System.out.println (s3 = = S4);//The result is falseTenSystem.out.println (S3.equals (S4));//result is true

On the string class, first of all, the string is a very high rate of use in the program class, in order to improve efficiency, the string is "pool" to manage.

String s1= "string"; This object is not in the heap, but in the string pool, when you create a variable sting s2= "string", the first to go to the pool, if the string exists, it is no longer new, but the S2 also point to the string, So S1 and S2 are pointing to the same object, so S1==s2 is true;

When string S3=new string ("string"), it is not the same, it is forced to create an object in the heap space, which does not point to the string pool, so s1==s3 is false; S1.equals (S3); String S4=new string ("string"); is another object created in heap space, S3==S4 is also false; S3.equals (S4); Is true.

Issue 2 Comparison of the String class equals and "= ="

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.