Java program to check whether string is palindrome

Let’s learn java program to check whether string is palindrome.

Java program to check whether string is palindrome

palindrome program in java is one of the common java interview question. 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.,

Here equalsIgnoreCase() method is used which compares this string to another string, ignoring case considerations. Here’s the syntax for equalsIgnoreCase() method.

public boolean equalsIgnoreCase(String anotherString)

equalsIgnoreCase() method returns true if the argument is not null and it represents an equivalent String ignoring case; false otherwise.

In the below string palindrome in java user enters a string as input using nextLine() method of Scanner class. This string is stored in String variable ‘strInput’.

Then input string is reversed using for loop. Then using if else user entered string and reversed string checked for string palindrome using equalsIgnoreCase() method. Let’s see string palindrome program in java.

// java program to check palindrome string
import java.util.*;
public class PalindromeStringInJava
{
   public static void main(String[] args) 
   { 
      String strInput, strReverse = "";
      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--)
      {
          strReverse = strReverse + strInput.charAt(a);
      }
      if(strInput.equalsIgnoreCase(strReverse))
      {
         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