Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to check the given number is PALINDROME or NOT.

Java Code Example — Simple Programs

ADVERTISEMENT

Java Program to check the given number is PALINDROME or NOT.

Objective

Write a Java program to check if an integer is a palindrome (reads the same forwards and backwards).

Algorithm / Approach

  1. Read an integer n from the user.
  2. Store the original value of n in a variable orig.
  3. Initialize an integer rev to 0.
  4. Start a while loop as long as n > 0.
  5. Extract the last digit using t = n % 10.
  6. Append it to rev using rev = (rev * 10) + t.
  7. Remove the last digit from n using n = n / 10.
  8. Compare orig with rev; if they match, it is a palindrome.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter a Num: ");
  int n = s.nextInt();
  int orig= n;
  int rev =0;
  while(n>0) {
   int t = n%10;
   rev = 10*rev+t;
   n = n/10;
  }
  if(orig==rev) {
   System.out.print("Palindrome");
  }
  else {
   System.out.print("NOT Palindrome");
  } 
 }
}

Expected Output

Enter a Num: 12321
Palindrome

Explanation of the Program

  • A palindrome reads the same in both directions (e.g., 12321).
  • To reverse the number, the program extracts the last digit using modulo 10 (% 10) and appends it to the reversed number.
  • Multiplying the current reversed number by 10 shifts its digits to the left, making room for the newly extracted digit.
  • Because the original n is destroyed during the loop, a copy (orig) is saved at the beginning for the final comparison.

Complexity

Time Complexity O(log10(n)) - Iterates exactly as many times as there are digits.
Space Complexity O(1)

Common Mistakes

  • Comparing rev against n instead of orig at the end. At the end of the loop, n is always 0.
  • Not saving the original value before the loop starts.
ADVERTISEMENT