开发者

String comparison in Java [duplicate]

开发者 https://www.devze.com 2023-02-16 06:13 出处:网络
This question already has answers here: How do I compare strings in Java? (23 answers) Closed 4 years ago.
This question already has answers here: How do I compare strings in Java? (23 answers) Closed 4 years ago.

I am working with Java code in JSP and I am trying to compare str开发者_Go百科ings and I am having problem with that.

I have declared two strings

s1 = "din";
s2 = "din";

However, the if (s1 == s2) never executes. Can someone help me?


The operator == for Strings compares for reference equality, not value equality.

Try calling equals instead of using ==:

if (s1.equals(s2)) { ... }


When comparing strings you should always use the equals method, not ==:

if(str1.equals(str2))

...would be the correct way to do things.

Where confusion arises is cases like the following:

String str1 = "hello";
String str2 = "hello";
System.out.println(str1==str2);

The above will actually print out true. However, save for academic purposes like the above, you shouldn't ever use it. If you're using == you're checking if the values are physically the same object on the heap. If you're using .equals() you're checking that they're meaningfully equal, even if they're actually two separate objects. Sometimes, especially where literals are involved such as above (or when you manually call the intern() method) Java will automatically make two separate string objects point to the same object for performance reasons. However, there's no logical guarantee this will happen (unless you want to bother yourself with explicit details of the JLS, and even then it's only guaranteed sometimes) and most of the time it won't. Take the following for example:

String str1 = "hello";
String str2 = "he";
str2 += "llo";
System.out.println(str1 == str2);

Now it prints false, because despite being meaningfully equal we haven't hit the same optimisation that Java was providing previously.

In both cases above, using ,equals() would return true.


You use 'equals' when you compare strings.

if(s1.equals(s2)) { true }


What are you trying to achieve?

Compare String's or their values? If you are expecting that your (if) condition should return true then use

s1.equals(s2);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号