Thursday, 16 February 2017

java - If statement using == gives unexpected result





private void refineWords() {
for(String word : words){
Log.i("word", word);
if (word == "s" || word == "t" || word == "am" || word == "is" || word == "are" || word == "was" || word == "were" || word == "has" ||
word == "have" || word == "been" || word == "will" || word == "be" || word == "would" || word == "should" || word == "shall" ||

word == "must" || word == "can" || word == "could" || word == "the" || word == "as" || word == "it" || word == "they" ||
word == "their" || word == "he" || word == "she" || word == "his" || word == "her" || word == "him" || word == "its" ||
word == "in" || word == "on" || word == "a" || word == "at") {

Log.i("step", "step Success!!");
words.remove(word);
}
}
}



I have a List called "words" and it contains strings. Here the Log.i works for the "word" tag fine but the "step" Statement does not executes. Seems the If condition does not work well. like this method never goes into it although the "words" list contains similar strings. What would be the problem. pleas help..


Answer



You need to use String.equals(), not ==. == checks if two Object references refer to the same Object:



if("s".equals(word) || "t".equals(word) || ...


From section 15.21.3 Reference Equality Operators == and != of the Java Language Specification 3.0:





While == may be used to compare references of type String, such an equality
test determines whether or not the two operands refer to the same String
object. The result is false if the operands are distinct String objects, even if
they contain the same sequence of characters. The contents of two strings s and t
can be tested for equality by the method invocation s.equals(t).



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...