Java Data Type Tutorial - Java String Algorithms








Testing a String for Palindrome

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 w  w .  ja  va 2  s  .  c o  m
  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.