1

So when I'm running this code with any word, it is always returning false. The first String accepts the word, and then it's changed to lower case. Then I'm building a new String out of it to compare it to another string that is appended as the reverse of the original word. Am I not seeing something, or can you tell me what's wrong with it?

public class Palindromes 
{
 public static void main(String[] args) 
 {
  int count = Integer.parseInt(args[0]);
  for(int i = 1; i <= count; i++)
  {
   System.out.print(isPalindrome(args[i]) + " ");
  }
 }
 public static boolean isPalindrome(String s)
 {
  String str = s.toLowerCase();
  StringBuilder orig_str = new StringBuilder(str);
  StringBuilder revStr = new StringBuilder();
  for (int i = str.length()-1; i >= 0; i--) 
  {
   revStr.append(orig_str.charAt(i));
  }
  boolean isPal = (revStr == orig_str);
  return isPal;
 }  
}
Eran
  • 387,369
  • 54
  • 702
  • 768
Santo
  • 13
  • 3

1 Answers1

3

Comparing two distinct StringBuilder instances with == would always give you false, regardless of their content, since they are not the same instance.

Try revStr.toString().equals(str)

It seems that StringBuilder doesn't override Object's equals, so you have to perform the equals on the Strings that result from the StringBuilders.

BTW, StringBuilder has a reverse method, so you can re-write your method in a single line :

public static boolean isPalindrome(String s) {
    return new StringBuilder(s.toLowerCase()).reverse().toString().equals(s.toLowerCase());
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Okay, I did change the boolean to revStr.equals(orig_str) but it still gives me a false value. – Santo Oct 25 '14 at 11:43
  • @Santo Fixed now. I didn't realize `StringBuilder` doesn't override `equals`. – Eran Oct 25 '14 at 11:49
  • I ended up with changing the revStr to a string after appending it. comparing them works fine now. Thanks a lot. – Santo Oct 25 '14 at 11:54