开发者

Weird Java Behaviour in string comparison [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Java string comparison?

I have encounter the following problem, I have an object called "lang", is a result from a method LanguageDetector.detect() which output a string.

lang = LanguageDetector.detect();

So I would want to check whether the language is english, so I am checking,

lang == "en"

The following screen is my debug screen, my lang is showing "en", however my lang == "en" is sh开发者_运维百科owing false and lang.toString() == "en" is false, does anyone encounter following problem before and have a possible solution?

Weird Java Behaviour in string comparison [duplicate]


Use equals() method of String object instead of direct comparison.

String first = new String("Hello");
String second = new String("Hello");

first == second will return false.

first.equals(second) will return true.


In Java, == always does a reference comparison. You need a value comparison though (with the equals() method for instance).


You're comparing the references to the Strings rather than the contents of the strings themselves. See here for more info.

Note that this issue doesn't apply just to Strings, but to all objects. As such, you may have to define appropriate equals() methods for any objects you create yourself.

Additionally String interning will confuse matters if you're not careful. See here for more details.


Use lang.equals("en") instead of lang == "en". The latter compares the two string references for equality, whereas the former compares the contents of the two strings.

See http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml for an overview of different string comparison methods in Java.


By using == you are checking that both string references point to the same object.

For strings that are created on the fly, and not interned, this will equal false.

To compare the strings for equality, letter by letter, use string1.equals(string2) or even string1.equalsIgnoreCase(string2).


Use "en".equals(lang) instead of lang == "en"


Its better to use the equals as said but if its necessary for performance reasons you can try the intern() function.

lang.intern() == "en"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜