Possible Duplicate:
How do I compare strings in Java?
I probably made a logical error somewhere but I do not know where.
The output is always FALSE even though the condition seem to be TRUE
public class Test {
public static void main(String[] args) {
String str1 ="Hello world";
String str2 ="Hello world";
if (checkSubstring(str1,str2)){
System.out.println("Cool");
}
else
System.out.println("Not cool");
}
static boolean checkSubstring(String str1, String str2) {
String s1 = str1;
String s2 = str2;
if (s1.substring(4)== s2.substring(4)){
return true;
}
else
return false;
}
}
You should always use
equalsmethod to test for the content ofstring.==operator checks whether tworeferenceare pointing to same object or different ones. And sinces1.substring()ands2.substring()will generate two different string objects, so comparing theirreferencewill give youfalseboolean value.So, in
checkSubstringmethod, you should compare your substring like this: –