Palindrome in Java | String Program

A palindrome in Java is a word, phrase, number, or sentence that reads the same in forward and backward directions.

In other simple words, a palindrome is a word, phrase, number, or sequence of characters that is the same after reversed (ignoring spacing, punctuations, and capitalization).

In palindrome, reading a string from left to right is the same as when reading from right to left. Some examples of palindromes are: mom, dad, noon, madam, 121, 38983, rotor, racecar, etc.

There are several ways to check whether a string is a palindrome or not. They are as follows:

  • String palindrome using For loop
  • Checking string palindrome using two variables
  • Testing string palindrome using Reverse method
  • String palindrome using Recursion
  • String, phrase, or sentence palindrome using Array

Basic Logic or Algorithm to check whether a string is palindrome:


There are the following points that must be considered in the palindrome program to check whether a string is a palindrome.

1. Prompt the user to enter a string or sentence.

2. Read the string or sentence and store it in string object.

3. Find the length of the string using length() method of String class.

4. Apply a loop to reverse every character of a string using charAt() method of String class.

5. Use equalsIgnoreCase() method to compare original string and reverse string.

6. Use if statement to display a message ” string is a palindrome or not”.

String Palindrome Program in Java using for loop


A string is a palindrome when it is read from a forward or backward direction, remains the same. Let’s create a program to check whether a given string is palindrome or not, using empty string logic and for loop.

Program code 1:

package stringProgram;
import java.util.Scanner;
public class StringPalindrome
{  
 public static void main(String[] args) 
 {
     String s, str = "";
// Create a scanner class to take input from keyboard.  
     Scanner a = new Scanner(System.in);
     System.out.print("Enter a string that you want to check: ");
      s = a.nextLine();

// Find the length of string using length() method of String class.    
     int l = s.length();
// Loop to get the reverse of string using charAt() method of String class.   
     for(int i = l - 1; i >= 0; i--)
     {
        str = str + s.charAt(i);
      }
// Condition to check whether two strings are equal and display the message.   
     if(s.equalsIgnoreCase(str))
           System.out.println("String " +str+ " is palindrome.");
     else
          System. out.println("String " +str+ " is not palindrome.");
 }
}

In this program, we have created a string, called s, and an empty string, called str. We created this empty string to concatenate each character after for loop to get the output in the console in the form of string. Otherwise, we may get the output something like this:

Output:
      m
      a
      d
      a
     m

Using concatenation logic, we can print the output as:

Output:
     Enter a string that you want to check: madam
     String madam is palindrome.
     Enter a string that you want to check: mom
     String mom is palindrome.
     Enter a string that you want to check: happy
     String yppah is not palindrome.

After the reversing string, we have compared two strings using equals() method. If the equals returns true, the string is a palindrome, else the string is not palindrome.

This is a simple empty string logic to check a string is palindrome or not. We have used charAt() method in the program that returns the character at the specified index.

An index ranges from 0 to length() – 1. The first character of the sequence is at index 0, the next at index 1,and so on in the array indexing. Let’s try another approach.

How to Check a String is Palindrome or not using two Variables?


In this approach, we will check whether the first character in the string is similar to the last character. If yes, check the second character is the same as the second-to-last character.

This process will continue until a mismatch gets found or all the characters in the string gets checked, except the middle character if the string contains the odd number of characters.

To implement this concept, we will take two variables i and j to point the position (or index) of two characters at the beginning and end of a string.

Initially, i is 0 and j is (l – 1). If two characters at these positions are the same, increment i by 1 and decrement j by 1. This process continues until i >= j or a mismatch found. If two characters at these positions do not match, a string is not a palindrome.

Program code 2:

package stringProgram;
import java.util.Scanner;
public class StringPalindrome
{  
// Create a function to check a string is palindrome or not.
    public static boolean isPalindrome(String str)
    {
// Index of the first character in a string.
     int i = 0;
// Find the length of string using length() method of String class.
     int l = str.length();
// Index of last character in the string.
     int j = l - 1;
     while(i < j)
     {	   
	if(str.charAt(i) != str.charAt(j)) 
	 return false; // Not a palindrome.
	 i++; // Increment first pointer. 
	 j--; // Decrement the other.
      }
	return true; // The string is palindrome.  
    }
 public static void main(String[] args) 
 {
// Create a Scanner class object.
     Scanner sc = new Scanner(System.in);
// Prompt the user to enter a string.
     System.out.println("Enter a string that you want to check: ");
     String s = sc.nextLine();

// Condition to display a message entered string is palindrome or not.    
     if(isPalindrome(s))
	    System.out.println("String " +s+ " is a palindrome.");
      else
	    System.out.println("String " +s+ " is not palindrome.");
   }
}
Output:
     Enter a string that you want to check: 
     mom
     String mom is a palindrome.
     Enter a string that you want to check: 
     Scientech
     String Scientech is not palindrome.

String Palindrome Program in Java using Reverse method


Let’s create a program where we will check a string is a palindrome or not using reverse() method of StringBuffer class.


In this approach, first we will reverse the sequence of characters in a buffer using reverse() method of StringBuffer class, and then we will compare the reverse sequence of characters with the original sequence of characters in both strings.

If match found, the string is a palindrome, else not. Look at the following source code to understand better.

Program code 3:

package stringProgram;
public class StringPalindrome
{  
 public static void main(String[] args) 
 {
   String str = "Madam";
   StringBuffer sb = new StringBuffer(str);
   String rev = sb.reverse().toString();
   if(rev.equalsIgnoreCase(str))
	System.out.println("String " +str+ " is a palindrome.");
   else
	System.out.println("String" +str+ " is not a palindrome.");  
 }
}
Output:
       String Madam is a palindrome.

String Palindrome in Java using Recursion and Scanner


Let’s create a recursive Java program in which we will check a string is palindrome or not, using recursion. The basic recursive definition or logic of a palindrome is as follows:

  • An empty string is a palindrome.
  • A single character string is a palindrome.
  • A string of length > 1 is a palindrome if and only if the first and last characters are identical.
  • The substring obtained by removing the first and last characters is also a palindrome.

If a string is a palindrome, then each recursive call will decrease the number of characters in the string by 2. Look at the following source code step by step.

Program code 4:

package stringProgram;
import java.util.Scanner;
public class StringPalindrome
{ 
// Create a function to check a string is a palindrome or not.	
   public static boolean isPalindrome(String str)
   {
 // Checking for null value.
	if(str == null)
	{
	    throw new IllegalArgumentException("String cannot be null");	
	}	
 // Find the length of a string.
      int len = str.length();
// In case of empty string or one character string, 
// we do not need to do comparison because they are always palindromes.	
     if(len <= 1)
     {
	 return true;  
      }
// Convert the string into uppercase to make the comparison case-insensitive.
     String newStr = str.toUpperCase();

// Get the first and last characters of a string.
     char first = newStr.charAt(0);
     char last = newStr.charAt(newStr.length() - 1);

// Get the substring of this string. 
// The substring starts at the specified beginIndex and ends to the character at index endIndex - 1.  
     String substring = newStr.substring(1, newStr.length() - 1);
      if(first == last)
      {
	   return isPalindrome(substring); // Recursive case.
       }
      return false;
    }
 public static void main(String[] args) 
 {
// Create a Scanner class object.	 
     Scanner sc = new Scanner(System.in);
// Prompt the user to enter a string.  
     System.out.print("Enter the string: ");
     String str = sc.nextLine();

// Condition to display palindrome message.  
     if(isPalindrome(str))
     {
	System.out.println(str + " is a palindrome");
     }
     else {
	 System.out.println(str + " is not a palindrome");
      }         
   }
}
Output:
      Enter the string: MADAM
      MADAM is a palindrome
      Enter the string: Java
      Java is not a palindrome

String Palindrome Program in Java using Array


Let’s create a program to check a sentence, phrase, or string is a palindrome or not, using Array and Scanner class.

Program code 6:

package stringProgram;
import java.util.Scanner;
public class StringPalindrome
{ 
// Create a function to check a sentence, phrase, or string is a palindrome or not.	
   public static void isPalindrome(String str)
   { 
     int i = 0;
     int len = str.length();
// Convert the sentence into lowercase to make comparison case-insensitive.  
     String s = str.toLowerCase();

// Create an object of char array of size len for original string.  
     char[] origCharArray = new char[len];
// Create an object of char array of size len for reverse string.    
     char[] revCharArray = new char[len];
  
// Put the original string or sentence in an array of chars.
    for(i = 0; i < len; i++)
    {
	origCharArray[i] = s.charAt(i);  
    }
// Now, reverse array of chars.
    for(int j = 0; j < len; j++)
    {
	revCharArray[j] = origCharArray[len - 1 -j];
    }
  String revs = new String(revCharArray);
  if(str.equalsIgnoreCase(revs))
       System.out.println(revs+ " is a palindrome.");
  else
      System.out.println(revs+ " is not  palindrome.");
}
 public static void main(String[] args) 
 {	 
// Create a Scanner class object.	 
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter a sentence, phrase, or string: ");
     String s = sc.nextLine();
     isPalindrome(s);
  
 }
}
Output:
     Enter a sentence, phrase, or string: 
     Dot saw I was Tod
     dot saw i was tod is a palindrome.

    Enter a sentence, phrase, or string: 
    Love Java Programming
    gnimmargorp avaj evol is not  palindrome.

In this approach, we have converted the string to an array of characters using first for loop, and reverse the array of characters into the second array of characters using second for loop.

Then, we have converted back to a string. After conversion, we have compared the original string with reverse string using equalsIgnoreCase() method. It returns true if the string or sentence is a palindrome, else returns false.

We can also use getChars() method of String class to convert a string or a portion of a string into an array of characters. So, we can replace the first for loop in the program with the following code:

s.getChars(0, len - 1, revCharArray, 0);

How to Check Palindrome Words in a Sentence in Java


Let’s create a program to enter a sentence using scanner class and display words from the sentence that are only palindrome. Look at the following source code to understand better.

Program code 7:

package stringProgram;
import java.util.Scanner;
public class StringPalindrome
{ 
// Create a function to check palindrome words in a sentence.	
public static void isPalindrome(String str)
{ 
   String word = "", rev = "";
   char ch;
   int len = str.length(); 
   for(int i = 0; i < len; i++)
   {
	ch = str.charAt(i);
        if(ch != ' ')
        {
          word = word + ch;
          rev = ch + rev;
        }
       else
      {
	  if(word.equalsIgnoreCase(rev)) 
	  System.out.println("Palindrome word: " +word);	 
	  word = "";
	  rev = "";
       }
    }
}
 public static void main(String[] args) 
 {	 
// Create a Scanner class object.	 
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a sentence: ");
    String s = sc.nextLine();
    isPalindrome(s);
 }
}
Output:
     Enter a sentence: 
     Mom and Dad are not at home.
     Palindrome word: Mom
     Palindrome word: Dad

In this tutorial, you learned string palindrome in Java with example programs. Hope that you will have understood the basic concepts of how to check whether a string is a palindrome or not.

In the next tutorial, we will learn how to check a number is a palindrome in Java.
Thanks for reading!!!
Next ⇒ Palindrome Number in Java⇐ Prev Next ⇒