Java program to check whether string is palindrome

In this post we are going to learn java program to check whether string is palindrome.Java program to check whether string palindrome is one of the common interview question.

How to check palindrome string in java

Palindrome string is a string where string remains same when reversed or a word spelled same way forwards and backwards.Example : level, dad, mom, madam, abcba, etc.,

Also read – merge sort in java

In the below java program user enters a string as input. Then input string is reversed using for loop. Here equalsIgnoreCase() method is used which compares this string to another string, ignoring case considerations.
public boolean equalsIgnoreCase(String anotherString)

Lastly this reversed string is compared with input string. Let’s see java program,
import java.util.*;

public class PalindromeStringInJava 
{
   public static void main(String[] args) 
   { 
      String strInput, strPalindrome = "";
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter the string : ");
      strInput = sc.nextLine();
      int num = strInput.length();
      for(int a = num - 1; a >= 0; a--)
      {
         strPalindrome = strPalindrome + strInput.charAt(a);
      }
      if(strInput.equalsIgnoreCase(strPalindrome))
      {
         System.out.println("String is palindrome.");
      }
      else
      {
         System.out.println("String is not palindrome.");
      }
      sc.close();
   }
}

Output:java program to check whether string is palindrome
Similarly we can execute above program without reversing a string. In this program characters at beginning and at end move towards middle of the string.
import java.util.Scanner;

public class PalindromeStringDemo 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string : ");
      String str = sc.nextLine();

      int length = str.length();
      int a, start, end, middle;

      start = 0;
      end = length - 1;
      middle = (start + end) / 2;

      for(a = start; a <= middle; a++) 
      {
         if(str.charAt(start) == str.charAt(end)) 
         {
            start++;
            end--;
         }
         else
         {
            break;
         }
      }
      if(a == middle + 1) 
      {
         System.out.println(str + " - palindrome string.");
      }
      else
      {
         System.out.println(str + " - not a palindrome string.");
      }
      sc.close();
   }
}

Output:Enter a string : level level – palindrome string.