1

I was testing out the substring capabilities in Java when I ran into an error. Although the substring's value is correct, it fails in an if statement. Here is my code:

public static void main(String[] args) {
    String foo="bar";
    String subFoo=foo.substring(0,1);
    System.out.println(foo);
    System.out.println(subFoo);
    if (subFoo=="b") {
        System.out.println("its b");
    } else if (subFoo!="b") {
        System.out.println("its not b");
    } else {
        System.out.println("who knows?");
    }

}

It is supposed to output the lines

bar
b
its b

when run, but instead prints

bar
b
its not b

Even though it prints subFoo correctly as "b" it doesn't seem to register properly in the if statement. Any ideas?

a52
  • 232
  • 2
  • 9
  • 3
    The bug is in your code. Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *objects* are the same 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 Mar 08 '15 at 03:25
  • @HovercraftFullOfEels technically it doesn't check "if the two objects are the same", it checks "if the two references are equal" (i.e. refer to the same object). – user253751 Mar 08 '15 at 03:41
  • @immibis: yep, that's better, thanks. – Hovercraft Full Of Eels Mar 08 '15 at 03:52
  • Interesting boolean logic... See also http://thedailywtf.com/articles/What_Is_Truth_0x3f_ – shmosel Mar 08 '15 at 04:18

0 Answers0