4

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 showing false and lang.toString() == "en" is false, does anyone encounter following problem before and have a possible solution?

Weird java problem

0

7 Answers 7

7

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. 
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, in your example, (first == second) will return true also. That's because all literal strings are interned. For your example to work, you would need something like String second = new String("Hello").
I have edited the answer to reflect this.
5

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

Comments

5

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.

Comments

3

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.

Comments

3

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).

Comments

2

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

Comments

1

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

lang.intern() == "en" 

1 Comment

Interesting approach - but this is, unfortunately, not very idiomatic Java (i.e. - if you sent me this in a code review, I'd probably tell you to do it "right" instead). In this case, the range of possible values for lang is small - but if done indiscriminately could cause a blow-up of the intern'd string pool.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.