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

Check whether given string is a palindrome or not 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.,

Also read – armstrong program in java

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.

Also read – string palindrome in java using array

In the below string palindrome in java user enters a string as input. Then input string is reversed using for loop.

Also read – integer palindrome in java

Here equalsIgnoreCase() method is used which compares this string to another string, ignoring case considerations.

Lastly this reversed string is compared with input string. Let’s see palindrome string program in java.

import java.util.*;
public class PalindromeStringInJava
{
   public static void main(String[] args) 
   { 
      String strInput, strReverse = "";
      Scanner sc = new Scanner(System.in);
      System.out.println("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

Also read – string palindrome in java without using reverse method

Also read – string palindrome in java using recursion


String palindrome in java using reverse method

Let’s learn string palindrome in java using reverse method. Here we are using reverse() method of Apache commons StringUtils class.

import org.apache.commons.lang3.StringUtils;
public class UsingReverseMethod
{
   public static void main(String[] args)
   {
      System.out.println(stringReverse("flowerbrackets"));
      System.out.println(stringReverse("mom") );
   }
   public static boolean stringReverse(String strGiven)
   {
      String strReverse = StringUtils.reverse(strGiven);
      return strGiven.equals(strReverse);
   }
}


Output:

false
true