String Palindrome In Java

String Palindrome In Java | A palindrome is a word or a string when you read it from left to right or right to left the word will spell the same. In Java, we can also find such numbers. The palindrome number is also based on the palindrome string. The reverse of a number is equal to the same number is called a palindrome number. Example:- 5225, 12321, and e.t.c.

Palindrome String Example

Before going to the coding let us see some examples of palindrome string:- radar, level, madam, civic, rotor, refer, and e.t.c. Observe these words they are the same when spelled backward also. R a d a r -> r a d a R

String Palindrome In Java Using reverse() Method

In Java, StringBuilder and StringBuffer classes contain a pre-defined reverse() method to reverse the string type values. The syntax of reverse() method in StringBuilder class:- public StringBuilder reverse()

String Palindrome In Java Using Reverse Method

import java.util.Scanner;

public class Palindrome {
   public static void main(String args[]) {
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter a string: ");
      String string = scan.nextLine();
      StringBuilder sb = new StringBuilder(string);
      sb.reverse();
      String data = sb.toString();
      if (string.equals(data)) {
         System.out.println("Palindrome");
      } else {
         System.out.println("Not Palindrome");
      }
      scan.close();
   }
}

Output:-

Enter a string: madam
Palindrome

Enter a string: KnowProgram
Not Palindrome

We have defined a class Palindrome and created a Scanner object to get input from the user. The input is taken as a string and converted as a StringBuilder object so that we can call the reverse() method. After reversing it, convert back the StringBuilder object to a String object. Now we will compare the original and resultant strings. If the reversed string is the same as the original string then print “Palindrome” or else print “Not Palindrome”. 

Note:- Here, we are calling the equals() method which compares strings based on content case-sensitive wise. For example:- “Madam” is not a palindrome case-sensitive wise, but it is a palindrome string case-insensitive wise. If we want to compare strings without caring about the case then we can call the equalsIgnoreCase() method.

if (string.equalsIgnoreCase(data)) {
   System.out.println("Palindrome");
} else {
   System.out.println("Not Palindrome");
}

Output:-

Enter a string: Madam
Not Palindrome

String Palindrome In Java Using Array

In the previous program, we used the reverse() method to convert a given string to its reverse format. Now, let us do the same by reversing the string manually. In the reverse string in Java, we have discussed different ways to reverse a string in Java programming.

import java.util.Arrays;
import java.util.Scanner;

public class Main {
   public static void main(String args[]) {
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter a string: ");
      String string = scan.nextLine();

      char[] reverse = string.toCharArray();
      int size = reverse.length;
      char[] original = Arrays.copyOf(reverse, size);

      for (int i = 0; i < size / 2; i++) {
         char temp = reverse[i];
         reverse[i] = reverse[size - i - 1];
         reverse[size - i - 1] = temp;
      }

      System.out.println("Original Array: " 
                         + Arrays.toString(original));
      System.out.println("Reverse Array: " 
                         + Arrays.toString(reverse));

      if (Arrays.equals(reverse, original)) {
         System.out.println("Palindrome");
      } else {
         System.out.println("Not a palindrome");
      }
      scan.close();
   }
}

Output:-

Enter a string: madam
Original Array: [m, a, d, a, m]
Reverse Array: [m, a, d, a, m]
Palindrome

Enter a string: KnowProgram
Original Array: [K, n, o, w, P, r, o, g, r, a, m]
Reverse Array: [m, a, r, g, o, r, P, w, o, n, K]
Not a palindrome

We have imported Arrays to perform array operations and a Scanner to read the input from the user. In the Main class, we asked the user to enter a string and read it using the scanner class. We have converted this string to an array of characters by using the toCharArray() method. We find the length of an array and store it in the “size” variable. We have used the Arrays.copyOf() method to store a copy of the array.

Now we want to reverse the original array of strings. For this, we have iterated the array using for loop and swapped the characters. Later we print the original array and reverse the array by the Arrays.toString() method. After that, we compare the original string and reversed string using the Arrays.equals() method. We find whether the reverse array is equal to an original array or not. If they are equal then print “Palindrome” or else print “Not a Palindrome”.

Longest Palindrome In a String Java

The below program tries to find the longest palindrome substring in a given string. If it is present then returns a particular substring. We have defined two methods longestPalindrome() and checkForEquality() method.

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter a string: ");
      String string = scan.nextLine();
      System.out.println("Longest Palindrome string: " 
                         + longestPalindrome(string));
      scan.close();
   }

   public static String longestPalindrome(String string) {
      if (string.isEmpty()) {
         System.out.println("Please enter a valid String.");
         return null;
      }
      if (string.length() == 1) {
         return string;
      }

      String longest = string.substring(0, 1);
      for (int i = 0; i < string.length(); i++) {
         String temp = checkForEquality(string, i, i);
         if (temp.length() > longest.length()) {
            longest = temp;
         }
         temp = checkForEquality(string, i, i + 1);
         if (temp.length() > longest.length()) {
            longest = temp;
         }
      }
      return longest;
   }

   public static String checkForEquality(String s1, int begin, int end) {
      while (begin >= 0 && end <= s1.length() - 1 
            && s1.charAt(begin) == s1.charAt(end)) {
         begin--;
         end++;
      }
      return s1.substring(begin + 1, end);
   }
}

Output:-

Enter a string: bananas
Longest Palindrome string: anana

Enter a string: abaradar121
Longest Palindrome string: radar

In the given string “abaradar121” there are three palindrome strings “aba”, “radar”, and “121”. Among them, “radar” is the longest palindrome string. Hence the output is “radar”.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *