Browse by Domains

Palindrome in Java: How to Check Palindrome Program?

A palindrome is a phrase, word, number, or sequence of characters that reads the same backward and forwards. This blog talks about how to check for a palindrome in Java with the help of a program. Before we learn about palindrome in Java, we will understand the concept of the palindrome.

Let’s get started!

  1. What is Palindrome?
  2. What is a Palindrome number?
  3. What is a Palindrome string?
  4. What is a Palindrome phrase?
  5. Palindrome Program in Java using while loops
  6. Palindrome Program in Java using for loops
  7. Palindrome Program in Java using recursion 
  8. Palindrome Program in Java using library method
  9. Conclusion
  10. Frequently Asked Questions

What is Palindrome?

A Palindrome is a word or phrase that is spelled the same even in the backward direction (ignoring spacing, punctuations, and capitalization).

A Palindrome number is a number that remains the same even after reversing, e.g., .161,24542,848, 38983. It is also a string or sequence of characters, i.e., it has the same sequence of letters when reading forwards and backward directions.

Example:

  • racecar
  • tenet
  • rotor
  • madam

What is a Palindrome Number?

A palindrome number is a number that remains the same when its digits get reversed. Ex: 15451, for example: If we take 131 and reverse it, then after reversing, the number remains the same.

Steps to Palindrome number program

  • Input the number from the user.
  • Then Reverse it.
  • Compare the number with the number entered by the user.
  • If both the no.’s are the same, then print the number as a palindrome
  • Else print, not a palindrome.

Palindrome Number Program in Java

import java.util.Scanner;

class expalindrome {
    public static void main(String args[]) {
        int x, number, y = 0, temp = 0;
        Scanner s = new Scanner(System.in);
        System.out.println("Enter any number: ");
        number = s.nextInt();
        x = number;
        while (number > 0) {
            x = number % 10;
            number = number / 10;
            temp = temp * 10 + x;
        }
        y = x; // Set y to the original number
        if (temp == y) {
            System.out.println("Number is Palindrome");
        } else {
            System.out.println("Not Palindrome");
        }
    }
}

Output:

Enter any Number:

161

Number is Palindrome

Deep dive into different Java concepts and upskill

Learn more about palindrome programming with the help of these Java interview questions.

What is a Palindrome String?

A Palindrome String is a string that remains the same when read in a forward or backward direction.

Java program to find if a string is a palindrome

public class Palindrome
{
    public static void main(String args[])
    {
        String x, y = "";
       Scanner a = new Scanner(System.in);
      System.out.print("Enter  string you want to check:");
     x = a.nextLine();
        int l = x.length();
       for(int k = l - 1; k >= 0; k--)
     {
          y = y + x.charAt(k);
      }
      if(x.equalsIgnoreCase(y))
        {
            System.out.println("The string is palindrome.");
        }
        else
        {
            System. out.println("The string is not a palindrome.");
        }
    }
}

Output:

Enter the string you want to check:

NeveroddorEVen

The string is a palindrome.

What is a Palindrome Phrase?

Palindrome may consist of a Sentence or Phrase  Ex: Mr. Kate ate my Silver worm”, “Do John see God?” . Punctuation, capital letters, and spaces are usually ignored for Ex: “cats live on no evil star”  and “Steps on no cats” include the spaces.

Java program to find if a sentence is a palindrome

public class GFG 
{ 
    // To check sentence is palindrome or not 
    static boolean sentencePalindrome(String str) 
    {     
        int j = 0; 
        int i = str.length()-1; 
          
        // Lowercase string 
        str = str.toLowerCase(); 
          
        // Compares character until they are equal 
        while(j <= i) 
        { 
              
            char getAtj = str.charAt(j); 
            char getAti = str.charAt(i); 
              
            // If there is another symbol in left 
            // of sentence 
            if (!(getAtj >= 'a' && getAtj <= 'z')) 
                j++; 
              
            // If there is another symbol in right  
            // of sentence 
            else if(!(getAti >= 'a' && getAti <= 'z')) 
                i--; 
              
            // If characters are equal 
            else if( getAtj == getAti) 
            { 
                j++; 
                i--; 
            } 
              
            // If characters are not equal then 
            // sentence is not palindrome 
            else 
                return false; 
        } 
          
        // Returns true if sentence is palindrome 
        return true;     
    } 
      
    // Driver program to test sentencePallindrome() 
    public static void main(String[] args)  
    { 
        String str = "Too hot to hoot."; 
        if( sentencePalindrome(str)) 
          System.out.println("Sentence is palindrome"); 
        else
          System.out.println("Sentence is not" + " " + 
                                         "palindrome"); 
    } 
}

Pre-requisites:

  1. Scanner class (to obtain user input) 
  2. Recursion 
  3. For loop
  4. While loop
  5. If – else statements

Palindrome Program in Java using while loops (integer)

Algorithm

  1. START
  2. Take input from the user or initialize it manually (num).
  3. Store the input in a new variable (element).
  4. Until num is not equal to zero, find the remainder of the num and store it in a variable (reverse).
  5. Divide the num by ten and repeat step 3 using a while loop.
  6. Check if the element is equal to the reverse.
  7. If it is equal,
    1. Print it is a palindrome
    2. Else print, it is not a palindrome.
  8. END

Code Snippet

import java.util.*;
class Main {
  public static void main(String[] args) {
    Scanner inp= new Scanner(System.in);
    System.out.print("Enter the number: ");
    int num= inp.nextInt();
 
    int reverse=0, element, remainder; 
    element = num;
 
    while(num!=0){
      remainder= num % 10;
      reverse = (reverse * 10) + remainder;
      num = num / 10;
    }
 
    if (element == reverse){
      System.out.println("Yes, it is palindrome");
    }
    else{
      System.out.println("No, it is not palindrome");
    }
  }
}

Conclusion: Here, a “while” loop is used to iteratively check the digits in the input until it becomes zero. Inside the while loop, the modulus of the number is taken. It is then stored in a variable reverse for every iteration to obtain the exact reverse of the input. Lastly, the reversed word is compared to the original number to conclude if it’s a palindrome or not.

Explanation:

For example, num = 252

Reminder=num%10252 % 10 = 225 % 10 = 52 % 10 = 2
reverse = (reverse * 10) + remainder(0 * 10) + 2 = 2(2 * 10) + 5 = 25(25 * 10) + 2 = 252
num = num / 10252 / 10 = 2525 /10 = 22 / 10 = 0
num!=025! = 0  [continue]2! = 0 [continue]0 = 0 [stop]

Therefore, reverse and num are ultimately equal, which proves to us that it is a palindrome.

Palindrome Program in Java using FOR loop (integer)

Algorithm

  1. START
  2. Take input from the user or initialize it manually (num).
  3. Store the input in a new variable (element).
  4. Until num is not equal to zero, find the remainder of the num and store it in a variable (reverse).
  5. Divide the num by ten and repeat step 3 using a FOR loop.
  6. Check if the element is equal to the reverse.
  7. If they are equal,
    1. Print it is a palindrome
    2. Else print, it is not a palindrome.
  8. END

Code Snippet

import java.util.*;
class Main {
  public static void main(String[] args) {
    Scanner inp= new Scanner(System.in);
    System.out.print("Enter the number: ");
    int num= inp.nextInt();
 
    int reverse=0, element, remainder; 
    element = num;
 
    for( ;num!=0;num/=10){
      remainder= num % 10;
      reverse = (reverse * 10) + remainder;
    }
 
    if (element == reverse){
      System.out.println("Yes, it is palindrome");
    }
    else{
      System.out.println("No, it is not palindrome");
    }
  }
}

Conclusion: Here, a for loop is used to iteratively check if the digits in the input until it becomes zero. The number’s modulus is taken inside the FOR loop and is stored in a variable reverse for every iteration. This is done to obtain the exact reverse of the input. Lastly, the reversed word is compared to the original number to conclude if it’s a palindrome or not.

EXPLANATION: 

For example, num = 2002

Reminder=num%102002 % 10 = 2200 % 10 = 020 % 10 = 02 % 10 = 2
reverse = (reverse * 10) + remainder(0 * 10) + 2 = 2(2 * 10) + 0 = 20(20 * 10) + 0 = 200(200 * 10) + 2 =2002
num = num / 102002 / 10 = 200200 /10 = 2020 / 10 = 22 / 10 = 0
num!=0200! = 0  [continue]20! = 0 [continue]2! = 0 [continue]0 = 0 [stop]

Therefore, reverse and num are ultimately equal, which proves us that it is a palindrome.

Palindrome Program in Java using recursion (with strings)

Algorithm

  1. START
  2. Take input from the user or initialize it manually (string).
  3. Check if the length is equal to zero or one
    1. Print it is a palindrome
  4. Check each character in substring from the front and rear; if found, equal
    1. Print it is a palindrome
  5. If steps 3 and 4 fail
    1. Print it is not Palindrome
  6. END

Code Snippet

import java.util.*;
class Main{
  public static boolean Palindrome(String a){
    if(a.length() == 0 || a.length() == 1){
      return true;
    } 
    if(a.charAt(0) == a.charAt(a.length()-1)){
      return Palindrome(a.substring(1, a.length()-1));
    }
      return false;
  }
 
  public static void main(String[]args){
    Scanner inp = new Scanner(System.in);
    System.out.print("Enter the string: ");
    String string = inp.nextLine();
    if(Palindrome(string)){
      System.out.println(string + " is a palindrome");
    }
    else{
      System.out.println(string + " is not a palindrome");
    }        
  }
}

Conclusion: Here, the string is recursively checked if the letters in the input have equal length. It is a palindrome string if it has no letters or just one letter. If it is more than one letter, then each character of the substring is checked. If the words are found equal, then the word is confirmed to be a palindrome.

EXPLANATION: 

For example, string= “malayalam”

1.If empty string or has only one letter PALINDROME
2.Else if first letter == last letter (m == m)PALINDROME
Increment from the first letter and decrement from the last letter, repeat step 2
3.ElseNOT A PALINDROME

Palindrome Program in Java using Library methods (strings)

Algorithm

  1. START
  2. Using the string reverse function, find out the reverse of the string.
  3. Compare it with the initial string.
  4. If both strings are the same,

            4.1 Print it is a palindrome

  1. Else
    1. Print it is not a palindrome
  2. END

Code Snippet

import java.util.*;
class Main{
  public static void Palindrome(String s){
    String reverse = new StringBuffer(s).reverse().toString();
    if (s.equals(reverse)){
      System.out.println("Yes, it is a palindrome");
    }
    else{
      System.out.println("No, it is not a palindrome");
    }
}
 
public static void main (String[] args){
  Palindrome("erre");
}
}

Conclusion: Here, a “string reverse” library method is used first to reverse the string. Then the reversed string and the original strings are compared to check if they are palindrome or not.

EXPLANATION: 

For example, string = “ERRE”

String ERRE
LIBRARY METHOD “.toString” IS USED
ReverseERRE
String == ReversePalindrome
String != ReverseNot a Palindrome

Wrapping Up

This brings us to the end of the blog on Palindrome in Java. Hope this helps you to up-skill your Java skills. Check out this complete tutorial on Java to become an expert in Java Programming.

To learn more about programming and other related concepts, check out the courses on Great Learning Academy

Frequently Asked Questions

What is the logic of palindrome?

The logic of a palindrome is simple, wherein if we take a number and reverse it, it still stays the same as the original number. For example, 10101 is a palindrome number as it is going to stay the same even if we reverse it.

What is a palindrome string example?

A string is known to be a palindrome when the reverse of it is the same as the original one. For example, “bob” is a palindrome as its reverse will also be ” bob “.

How do you check if a given string is a palindrome or not?

To check if a string is palindrome or not, we can use the isPalindrome() function. We input the desired string as an argument, and if the function returns true, then the string is a palindrome; if it returns false, it is not a palindrome.

What is the longest palindrome word?

The longest palindromic word is the Finnish word “saippuakivikauppias” which contains 19 letters and typically means “dealer in lye”.

Engaging in the study of Java programming suggests a keen interest in the realm of software development. For those embarking upon this journey with aspirations towards a career in this field, it is recommended to explore the following pages in order to acquire a comprehensive understanding of the development career path:

Software engineering courses certificates
Software engineering courses placements
Software engineering courses syllabus
Software engineering courses fees
Software engineering courses eligibility
Avatar photo
Great Learning
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

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

Great Learning Free Online Courses
Scroll to Top