__java string comparison in Java

Source: Internet
Author: User
People who are familiar with C + + must know the code for two string comparisons:
(STRING1==STRING2)
But in Java, this code returns false even if the two strings are exactly the same
String1.equals (string2) must be used in Java to judge

Add
If:
String S1=new string ("Hello");
String S2=new string ("Hello");
Then (S1==S2) =false

If:
String s1= "Hello";
String s2= "Hello";
Then (S1==S2) =true;
Because they point to the same object.

If the values of other variables are assigned to S1 and S2, false is returned, even if the content is the same, because it is not pointing to the same object. So it is recommended to use Equals (), because equals is the real content.

For example:
String1= "AAA";
String2= "AAA";
The two strings should of course be equal.
If string1==string2 with an expression, the value of the expression is false
If the expression is String1.equals (string2), the value of the expression is true
So you should use String1.equals (string2), which in the IF statement is
if (String1.equals (string2) ==true)//String equal, ...

String1==string2, is equal value, and the memory address is equal, is completely equal
String1.equals (string2) is true, only values are equal

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.