Testing a String for a Palindrome - Java Language Basics

Java examples for Language Basics:String

Description

Testing a String for a Palindrome

Demo Code

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

    String str2 = "noon";
    boolean b2 = Main.isPalindrome(str2);
    System.out.println(str2 + " is a palindrome: " + b2 );
  }//from  w w w .j  a v  a2  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();
    if (len <= 1) {
      return true;
    }

    // Convert the string into uppercase, 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 comparison to be done 
    int counter = len / 2;

    for (int i = 0; i < counter; i++) {
      if (newStr.charAt(i)!= newStr.charAt(len - 1 - i)) {
        result = false;
  
        // Exit the loop 
        break;            
      }
    }
    return result;
  }
}

Result


Related Tutorials