Palindrome string in java

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn palindrome string in java.palindrome string javaPalindrome 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 – palindrome program in java using library methods

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 to check whether a string is a palindrome or not,
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:Please enter the string : mom 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.

Related Posts