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!
- What is Palindrome?
- What is a Palindrome number?
- What is a Palindrome string?
- What is a Palindrome phrase?
- Palindrome Program in Java using while loops
- Palindrome Program in Java using for loops
- Palindrome Program in Java using recursion
- Palindrome Program in Java using library method
- Conclusion
- 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:
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;
}
if(temp==y)
{
System.out.println("Number is Palindrome");
}
else
{
System.out.println("not Palindrome");
}
}
}
Output:
Enter any Number:
161
Number is Palindrome
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:
- Scanner class (to obtain user input)
- Recursion
- For loop
- While loop
- If – else statements
Palindrome Program in Java using while loops (integer)
Algorithm
- START
- Take input from the user or initialize it manually (num).
- Store the input in a new variable (element).
- Until num is not equal to zero, find the remainder of the num and store it in a variable (reverse).
- Divide the num by ten and repeat step 3 using a while loop.
- Check if the element is equal to the reverse.
- If it is equal,
- Print it is a palindrome
- Else print, it is not a palindrome.
- 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%10 | 252 % 10 = 2 | 25 % 10 = 5 | 2 % 10 = 2 |
reverse = (reverse * 10) + remainder | (0 * 10) + 2 = 2 | (2 * 10) + 5 = 25 | (25 * 10) + 2 = 252 |
num = num / 10 | 252 / 10 = 25 | 25 /10 = 2 | 2 / 10 = 0 |
num!=0 | 25! = 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
- START
- Take input from the user or initialize it manually (num).
- Store the input in a new variable (element).
- Until num is not equal to zero, find the remainder of the num and store it in a variable (reverse).
- Divide the num by ten and repeat step 3 using a FOR loop.
- Check if the element is equal to the reverse.
- If they are equal,
- Print it is a palindrome
- Else print, it is not a palindrome.
- 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%10 | 2002 % 10 = 2 | 200 % 10 = 0 | 20 % 10 = 0 | 2 % 10 = 2 |
reverse = (reverse * 10) + remainder | (0 * 10) + 2 = 2 | (2 * 10) + 0 = 20 | (20 * 10) + 0 = 200 | (200 * 10) + 2 =2002 |
num = num / 10 | 2002 / 10 = 200 | 200 /10 = 20 | 20 / 10 = 2 | 2 / 10 = 0 |
num!=0 | 200! = 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
- START
- Take input from the user or initialize it manually (string).
- Check if the length is equal to zero or one
- Print it is a palindrome
- Check each character in substring from the front and rear; if found, equal
- Print it is a palindrome
- If steps 3 and 4 fail
- Print it is not Palindrome
- 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. | Else | NOT A PALINDROME |
Palindrome Program in Java using Library methods (strings)
Algorithm
- START
- Using the string reverse function, find out the reverse of the string.
- Compare it with the initial string.
- If both strings are the same,
4.1 Print it is a palindrome
- Else
- Print it is not a palindrome
- 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 | |
Reverse | ERRE |
String == Reverse | Palindrome |
String != Reverse | Not 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
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.
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 “.
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.
The longest palindromic word is the Finnish word “saippuakivikauppias” which contains 19 letters and typically means “dealer in lye”.