Java Data Type How to - Test a String for Palindrome








Question

We would like to know how to test a String for Palindrome.

Answer

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

The following code shows how to check if a string is palindrome.

public class Main {
  public static void main(String[] args) {
    String str2 = "noon";
    System.out.println(isPalindrome(str2));
  }//from w ww . j  a v a  2s . com
  public static boolean isPalindrome(String inputString) {
    int len = inputString.length();
    if (len <= 1) {
      return true;
    }
    String newStr = inputString.toUpperCase();
    boolean result = true;
    int counter = len / 2;
    for (int i = 0; i < counter; i++) {
      if (newStr.charAt(i) != newStr.charAt(len - 1 - i)) {
        result = false;
        break;
      }
    }
    return result;
  }
}

The code above generates the following result.