Possible Duplicate:
How do I compare strings in Java?
i have written some code which compares two strings “abc” and “de”. The string abc is parsed and returned to “doc” to ext and then it is compared. Although it seems that if condition is true but still the else part is executing. where i am not getting plz help me ….thanks a lot.
public class xyz{
String abc="doc2.doc";
String de="doc";
public static void main(String arg[]){
xyz c=new xyz();
String ext = null;
String s =c.abc;
String d =c.de;
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1){
ext = s.substring(i+1).toLowerCase();
}
System.out.println(ext);
if(ext==d){
System.out.println("true");
}
else{
System.out.println("false");
}
}
}
You cannot compare strings with == as they are different objects.
The contents may be the same, but that is not what == looks at.
Use the equals method on one of the strings to compare it to the other string.
In your code, use:
If you ever need to compare two strings, and only one of them is a variable, I suggest the following approach:
This way you can be sure that you will not be calling equals on a Null object.
Another possibility is to use the compareTo method instead of the equals method which is also found in some other Java classes. The compareTo method returns 0 when the strings match.
You can find more information about strings in Java here.