Reputation: 2466
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 ! ! !
Upvotes: 3
Views: 441
Reputation: 383746
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
.
Upvotes: 1
Reputation: 17472
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.
Upvotes: 3
Reputation: 38531
if( "mango".equals("mango") ) {
return true;
}
Be careful not to use == for string comparisons in Java unless you really know what you're doing.
Upvotes: 4
Reputation: 15750
Why not just use the built-in String equals()
method?
return var1.equals(var2);
Upvotes: 5