Java string comparison

Source: Internet
Author: User

"= =" compares the memory addresses of two objects, while the Equals method compares the memory addresses of two objects by default.

1.String str = "Hello" generated string, first of all to check the string constant pool in the existence of the "hello", if present, will not create a new "Hello", directly return to the constant pool of this string address, if not exist, Then add this string to the string constant pool. A string constant pool that exists in the method area.

2.String str = new string ("Hello"), first of all in the constant pool looking for the existence of this string, the existence is no longer established, if not exist, then set up, and then copy to the heap memory! In heap memory new A string, of course, if the new string, Then their memory addresses are different. But for new strings, they are the same when using equals, because the method of overriding equals in string is to compare each char with a string to a char array, and finally to go true or    False. The new String creates two of this object altogether. One in the constant pool, one in heap memory!

3. String comparison tips:

Use "China". Equals (str), with the constant equals, to prevent null pointer exceptions from occurring. The method call is not empty.

Java string comparison

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.