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

Introduction to Palindrome in Java

The word “palindrome” has a Greek origin, a word, number, or set of characters that reads the same forward and backwards. Some examples of a palindrome are MALAYALAM, 343, 2001002, etc. Palindrome in Java can be implemented using many ways. Here we will discuss some important ways: 

  • Using while loops
  • Using for loops
  • Using recursion 
  • Using library method

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 No. is a number that remains the same even after reversing Ex:.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 direction. Example :

  • racecar
  • tenet
  • rotor
  • madam

What is a Palindrome Number?

Palindrome no. is the 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;
}
if(temp==y)
{
System.out.println("Number is Palindrome");
}
else
{
System.out.println("not Palindrome");
}
}
}


OUTPUT:

Enter any Number :

161

Number is Palindrome

What is a Palindrome String?

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

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' &amp;&amp; getAtj <= 'z')) 
                j++; 
              
            // If there is another symbol in right  
            // of sentence 
            else if(!(getAti >= 'a' &amp;&amp; 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 initialise it manually (num).
  3. Store the input in a new variable (element).
  4. Until num is not equal to zero, find the reminder 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 reverse.
  7. If it is equal,
    1. Print it is palindrome
    2. Else print it is not 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");
    }
  }
}

OUTPUT

1.1.JPG
1.2.JPG

Conclusion: Here, a “while” loop is used to iteratively check if 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 initialise it manually (num).
  3. Store the input in a new variable (element).
  4. Until num is not equal to zero, find the reminder 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 palindrome
    2. Else print it is not 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");
    }
  }
}

OUTPUT

2.1.JPG

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 initialise 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 palindrome
  5. If steps 3 and 4 fails
    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");
    }        
  }
}

OUTPUT

3.1.JPG
3.2.JPG

Conclusion: Here, the string is recursively checked if the letters in the input have equal length. If it has no letters or just one letter, then it is a palindrome string. 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 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");
}
}

OUTPUT       

4.1.JPG

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

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

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

9 − one =