Java - String Palindrome Testing

Problem

A palindrome is a word, a verse, a sentence, or a number that reads the same in forward and backward directions.

For example, "Able was I ere I saw Elba" and 1991 are examples of palindromes.

Solution

The following is the description of the steps to be performed inside the method.

Assume that the number of characters in the input string is n. You need to compare the character at indexes 0 and (n-1), 1 and (n -2), 2 and (n - 3), and so on.

You need to compare the characters only halfway through.

If all comparisons for equality returns true, the string is a palindrome.

Demo

public class Main {
  public static void main(String[] args) {
    String str1 = "hello";
    boolean b1 = isPalindrome(str1);
    System.out.println(str1 + " is a palindrome: " + b1);

    String str2 = "noon";
    boolean b2 = isPalindrome(str2);
    System.out.println(str2 + " is a palindrome: " + b2);
  }//from   w  w  w.j av a  2  s.  c o  m

  public static boolean isPalindrome(String inputString) {
    // Check for null argument.
    if (inputString == null) {
      throw new IllegalArgumentException("String cannot be null.");
    }

    // Get the length of string
    int len = inputString.length();

    // In case of an empty string and one character strings,
    // we do not need to do any comparisons.
    // They are always palindromes.
    if (len <= 1) {
      return true;
    }

    // Convert the string into upper case,
    // so we can make the comparisons case insensitive
    String newStr = inputString.toUpperCase();

    // Initialize the result variable to true
    boolean result = true;

    // Get the number of comparisons to be done
    int counter = len / 2;

    // Do the comparison
    for (int i = 0; i < counter; i++) {
      if (newStr.charAt(i) != newStr.charAt(len - 1 - i)) {
        // It is not a palindrome
        result = false;

        // Exit the loop
        break;
      }
    }

    return result;
  }
}

Result

Exercise