1

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;
 }
}
Community
  • 1
  • 1
AchillesVan
  • 4,156
  • 3
  • 35
  • 47
  • 3
    [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Baz Nov 11 '12 at 14:22

3 Answers3

6

You should always use equals method to test for the content of string.

== operator checks whether two reference are pointing to same object or different ones. And since s1.substring() and s2.substring() will generate two different string objects, so comparing their reference will give you false boolean value.

So, in checkSubstring method, you should compare your substring like this: -

if (s1.substring(4).equals(s2.substring(4))) {
    return true;
} else {
    return false;
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

s1.substring(4)== s2.substring(4)

In the above Change it to s1.substring(4).equals( s2.substring(4))

- Objects in Java are compared using the equals() method.

- As String is an Object in Java, it must be treated in the same way.

- Moreover if you are trying to compare 2 String irrespective of their Case, then use equalsIgnoreCase().

- "==" is used for comparing the primitive types, and also to check whether 2 Object Reference Variables are pointing on the same object on the heap or not.

Eg:

Dog d1 = new Dog();
Dog d2 = d1;

if (d1 == d2){}
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
1

you need equals function

static boolean checkSubstring(String str1, String str2) {

    String s1 = str1;
    String s2 = str2;
    if (s1.substring(4).equals(s2.substring(4))){
    return true;    
    }
    else
    return false;
}
Ankur
  • 12,676
  • 7
  • 37
  • 67