0

I am building a class that checks if the input contains palindromes and returns only the palindrome terms if they exist. I have been able to develop the following, and it compiles and runs without errors, but I am not getting any return from it.

Can anyone spot where my error lies?

public class Palindrome {

public static boolean isPalindrome(String word) {

    String back = word.charAt(word.length() - 1) + "";
    for (int i = word.length() - 2; i >= 0; i--) {
        back = back + word.charAt(i);
    }
    if (word == back) {
        return true;
    }
    return false;
}


public static void main(String[] args) {
    for (int i = 0; i < args.length; i++) {
        if (isPalindrome(args[i]) == true) {
            System.out.println(args[i]);
        }
    }

}

}

I believe the issue lies in the main method, specifically within the if statement, but I'm not exactly sure why it's not working.

public static void main(String[] args) {
    for (int i = 0; i < args.length; i++) {
        if (isPalindrome(args[i]) == true) {
            System.out.println(args[i]);
        }
    }

}

Thank you in advance for any help offered. I appreciate your time!

  • 1
    You can check for palindromes much more efficiently by doing it in place. But that's another question. The big O of this implementation is actually n^2. – Daniel Williams Sep 04 '13 at 23:15

4 Answers4

1

Seconded on the .equals() error.

Also, you can easily check for palindromes by using the built-in String reversal procedure:

String a = "sampleelpmas";
String b = new StringBuffer(a).reverse().toString();

a.equals(b); //TRUE
SWPhantom
  • 674
  • 5
  • 18
1

For the first part, you could reverse it using back = new StringBuilder(word).reverse().toString(), which is cleaner code and also more optimized (also faster but doesn't matter here).

But your problem is at comparing strings, == check if both objects are equal and this is never true for 2 strings, even if they're the same like you were expecting. Use word.equals(back), which check if text contents of string match.

Marko Gresak
  • 7,950
  • 5
  • 40
  • 46
0

Common error. Comparison of string is wrong. Do not use == operator. Use equals() method.

Change word == back to word.equals(back).

Rest should be right.

Pawel
  • 1,457
  • 1
  • 11
  • 22
0

You shouldn't use == to evaluate String equality, use equals() instead.

if (word.equals(back))
MasterOfBinary
  • 245
  • 1
  • 12