3

I am facing a very basic problem. Some time small things can take your whole day :( but thank to stackoverflow memebers who always try to help :)

I am trying to match 2 strings if they match it should return TRUE

now I am using this

if (var1.indexOf(var2) >= 0) {
return true;
}

But if var1 has value "maintain" and var2 has value "inta" or "ain" etc. it still return true :(. Is there any way in java that can do full text matching not partial? For example

if("mango"=="mango"){
return true;
}

thanks ! ! !

4 Answers 4

5

Why not just use the built-in String equals() method?

return var1.equals(var2);
Sign up to request clarification or add additional context in comments.

Comments

4
if( "mango".equals("mango") ) { 
   return true;
}

Be careful not to use == for string comparisons in Java unless you really know what you're doing.

2 Comments

== is comparing what the references point to, and .equals in the case of String is comparing the Strings lexicographically. In Java, you can create two new Strings that have the same content, and == will return false. In the contrived example you wrote, using == will most likely appear to work correctly, but if you created two String variables with the new operator and set the value to mango, it wouldn't work.
Here's a very rough analogy: var1 == var2 is like asking if two people are the same person, while var1.equals(var2) is like asking if two people have the same name.
3

use equals or equalsIgnoreCase on java.util.String for matching strings. You also need to check for null on the object you are comparing, I would generally prefer using commons StringUtils for these purposes. It has very good utils for common string operations.

Comments

1

Here's an example to show why == is not what you want:

String s1 = new String("something");
String s2 = new String("something");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

In effect, while s1 and s2 contains the same sequence of characters, they are not referring to the same location in memory. Thus, this prints false and true.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.