Question 2 Comparison Between String equals and "=", stringequals

Source: Internet
Author: User

Question 2 Comparison Between String equals and "=", stringequals

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

"Equals in String"Content of the comparison object

"Equals in Object"If the equals method is not rewritten, it is equivalent to "="; if the object content is compared, the equals method must be rewritten, because in practical applications, the comparison of object content is mostly performed. (See question 1)

 

1 String s1 = "String"; 2 String s2 = "String"; 3 String s3 = new String ("String"); 4 String s4 = new String ("String "); 5 System. out. println (s1 = s2); // The result is true 6 System. out. println (s1 = s3); // The result is false. 7 System. out. println (s1.equals (s2); // The result is true 8 System. out. println (s1.equals (s3); // The result is true 9 System. out. println (s3 = s4); // The result is false10 System. out. println (s3.equals (s4); // The result is true.

 

For the String class, let's talk about the String pool. strings are classes with high usage in programs. To improve efficiency, strings are managed by "pools.

String s1 = "String"; this object is not in the heap, but in the String pool. When you create another variable, Sting s2 = "String";, the object is first found in the pool, if this string exists, it will not be created, but s2 will also point to that string, so s1 and s2 will point to the same object, so s1 = s2 is true;

When String s3 = new String ("String"); It is different. This is to force an object to be created in the heap space and does not point to the String pool, so s1 = s3 is false; but s1.equals (s3); is true; String s4 = new String ("String"); is to create another object in the heap space, s3 = s4 is also false; but s3.equals (s4); is true.

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.