0

I'm writing some codes that test if there is "xx" in a string. For instance, doubleX("aaxxbb") should return true, and doubleX("axabb") should return false.

Here is my code:

private static boolean doubleX(String str) {
  for(int i=0;i<str.length()-1;i++){
      System.out.println(str.substring(i,i+2));
      if(str.substring(i,i+2) == "xx") return true;
  }
  return false;
}

Why does doubleX("aaxxbb") return false?

3 Answers3

2

You have to use .equals instead of ==. For more information, follow the duplication message.

return str.contains("xx");

Is a lot clearer though.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
1

You should understand the difference between == and equals: the first one compares references, the second compares actual values.

Your code is wildly inefficient.

I'd try something like this:

private static boolean doubleX(String str) {
    return (str.indexOf("xx") != -1);
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
0

Use equals() for checking the content of a String to another rather than ==. == checks for reference equality.

private static boolean doubleX(String str) {
        for(int i=0;i<str.length()-1;i++){
            System.out.println(str.substring(i,i+2));
            if(str.substring(i,i+2).equals("xx")) return true;
        }
        return false;
      }

Even you can directly code like:

private static boolean doubleX(String str) {
        return str.contains("xx");
      }
Trying
  • 14,004
  • 9
  • 70
  • 110