Java Program to check Palindrome String

By | August 26, 2017
This is a Java program to check if a string is a palindrome or not. A a string is a palindrome if it remains unchanged when reversed, for example “mam” is a palindrome as reverse of “mam” is “mam” whereas “public” is not a palindrome. Some other palindrome strings are “dad”, “madam”, “abcba”.

Note: Approach to check if a number is a palindrome is different from the approach to check palindrome string.

import java.util.*;

class Palindrome
{
	public static boolean isPalindrom(char[] word) {
		int i1 = 0;
		int i2 = word.length - 1;
		while (i2 > i1) {
			if (word[i1] != word[i2]) {
				return false;
			}
			++i1;
			--i2;
		}
		return true;
	}

   public static void main(String args[])
   {
      String string;
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter a string to check if it is a palindrome");
      string= in.nextLine();

      if (isPalindrom(string.toCharArray()))
         System.out.println("String is a palindrome.");
      else
         System.out.println("String is not a palindrome."); 
   }
}