0

I try to compare two strings in Java as the following:

        String a="String 1";
        String b = "String 1";
        if(a==b)
        {
            System.out.println("Equal");
        }
        else
            System.out.println("Not Equal");
        System.out.println("----------------");
        if(a.equals(b))
            System.out.println("Equal");
        else
            System.out.println("Not Equal");

I got warning message in NetBeans when I use a==b. Why it like this? But, when I use equals, it has no problem.

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
HENG Vongkol
  • 883
  • 1
  • 8
  • 10
  • 3
    Netbeans is trying to protect you from making a common mistake which will, most likely, not result in the outcomes you are expecting... – MadProgrammer Nov 11 '14 at 02:15
  • 1
    Don't compare Strings using `==`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two references refer to the very same *object* which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Nov 11 '14 at 02:21
  • Oh, so == and equals is not the same. I think they are the same because I get the same result. – HENG Vongkol Nov 11 '14 at 02:26
  • @HENGVongkol When comparing String literals, they're equal references because of string interning. But as a rule of thumb, always use `equals()`. – August Nov 11 '14 at 02:36
  • Try comparing `String foo1 = new String("Foo");` vs. `String foo2 = new String("Foo");`, and then tell me that they work the same. – Hovercraft Full Of Eels Nov 11 '14 at 03:09

0 Answers0