Are you looking for Java palindrome checker code or how to program it?

Before diving straight into the code, lets first understand what palindrome means-

In terms of number: A palindrome number is a number that remains same upon reversing it. For example, numbers 545, 151, 34543, 343, 171, 48984 etc are the palindrome numbers.

In terms of words: A word(or string) can also be palindrome. Just like numbers its remains same weather you read from left to right or right to left. In other words the reverse of the words remains same. For example, LOL, MADAM etc.

Algorithm for Java Palindrome Number-

  1. Get the number to check for palindrome.
  2. Hold the number in temporary variable.
  3. Reverse the number.
  4. Compare the temporary number with reversed number.
  5. If both numbers are same, print “palindrome number”.
  6. Else print “not palindrome number”.

How to Check for Palindrome Number in Java?

The below java code checks if the number is palindrome or not. Please note(line 4) the number that needs to be checked is 454 , it is assigned to the variable n.

class Palindrome{  
 public static void main(String args[]){  
  int r,sum=0,temp;    
  int n=454;//user input
  temp=n;    
  while(n>0){    
   r=n%10;  //getting remainder  
   sum=(sum*10)+r;    
   n=n/10;    
  }
  temp=n;    
  if(temp==sum)    
   System.out.println("palindrome number ");    
  else    
   System.out.println("not palindrome");    
 }  
}  

Output:

palindrome number

Here is the dry run of the reverse block-

  • 1st iteration: n = 454; r = n%10 = 4; sum = (sum*10)+r = 4; n = n/10 = 45;
  • 2nd iteration: n = 45; r = n%10 = 5; sum = (4*10)+5 = 45; n = n/10 = 4;
  • 3rd iteration: n = 4; r = n%10 = 4; sum = (45*10)+4 = 454; n = n/10 = 0;

As the value of n becomes 0, the condition will fail in while loop block. Therefore the loop will terminate.
The reverse block can be implemented using different types of loops.

Java offers mainly 3 types of Loop-

  1. while loop
  2. for loop
  3. do-while loop

Java Program Palindrome Using While Loop

As shown in the example above:

while(n>0){ 
  r=n%10;//getting remainder 
  sum=(sum*10)+r; 
  n=n/10; 
}

Java Program Palindrome Using do-While

In this case, we have to explicitly take care of a number less or equal to 0 in the first iteration. Therefore, do-while is not very appropriate for solving this problem.

do{ 
  if(n <= 0)
     break;
  r=n%10;//getting remainder 
  sum=(sum*10)+r; 
  n=n/10; 
}while(n>0);

Palindrome using Java For-Loop

If we replace the while loop block in the above example with the for-loop block given below the program would remain the same. Though someone can feel awkward to use such for-loop syntax without initialization, it seems to be the smallest solution to the Java Program Palindrome.


for(;n>0;n=n/10){
  r=n%10;//getting remainder 
  sum=(sum*10)+r;  
}

Java Palindrome String | Another way to find it is Palindrome or Not

import java.util.*;   
class Palindrome2  
{  
   public static void main(String args[])  
   {  
      String original, reverse = ""; //           1.Objects of String class  
      Scanner in = new Scanner(System.in); //     2.Object of scanner class for console based user input 
      System.out.println("Enter a string/number to check if it is a palindrome");  
      original = in.nextLine(); //                3.read next Line  
      int length = original.length(); //          4.length of string entered   
      for ( int i = length - 1; i >= 0; i-- ) //  5.iterate for length number of times 
         reverse = reverse + original.charAt(i);//6.create reverse string by reading string from end to begin
      if (original.equals(reverse))             //7.compare original and reversed string
         System.out.println("Entered string/number is a palindrome.");  
      else  
         System.out.println("Entered string/number isn't a palindrome.");   
   }  
}  

Output:

Enter a string/number to check if it is a palindrome
madam
Entered string/number is a palindrome.

As provided in the comments above, we follow 7 simple steps to implement a Palindrome check for both String and Number:

  1. create objects of String class named original and reverse.
  2. create an object of Scanner class to accept console input from the user.
  3. read input from the console using nextLine() to accept a String.
  4. length of String entered is stored in a variable named length of type int.
  5. run a loop from (length-1) to 0 to iterate backward through the String.
  6. create reverse String by reading each character at a time.
  7. write the conditional statement to check if the original and reverse are the same.

Whether String or Number the algorithm for the Palindrome program remains the same.

Using Java Stack to check Palindrome

Since Stack follows the LIFO mechanism (Last in First out). It works quite well to reverse the given input. We simply push the given input character by character in the stack and pop out each character building the reverse String until no more characters are left in Stack.

import java.util.Scanner;
import java.util.Stack;

class Palindrome2{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter number/word to check for palindrome: ");
		String input = sc.nextLine();
		String rev = "";
		Stack inputStack = new Stack();
		for(int i = 0; i<input.length() ; i++) {////push the given input character by character in the stack 
			inputStack.push(""+input.charAt(i));
		}
		for(int i = 0; i<input.length() ; i++) {////pop out each character building the reverse String until no more characters are left in Stack.
			rev += inputStack.pop();
		}
		if(input.equals(rev))
			System.out.println("Palindrome");
		else
		    System.out.println("not Palindrome");
	}
}

Java Program Palindrome using recursion

class PalindromeUsingRecursion{
  public static boolean isPal(String s)
    {   // if length is 0 or 1 then String is palindrome
        if(s.length() == 0 || s.length() == 1)
            return true; 
        if(s.charAt(0) == s.charAt(s.length()-1))
        return isPal(s.substring(1, s.length()-1));
        return false;
    }
}

Here in every recursive call, we check if the length of the string entered is ‘0’. If so, we return true else we check if the first character is the same as the last character. Again if true, we call the same function by trimming the first and last character [s.substring(1, s.length()-1)]. if false, we return false. This is a simple and powerful solution to the Java Palindrome Program.

History of Palindrome

Palindromes have a considerable history. They date back to about 70 AD—the first palindromes were found as graffiti at Herculaneum. The first known palindrome was written in Latin and dates back to Roman times. Moreover, palindromes were also found in ancient Sanskrit, as well as in ancient Greek.