Java Program for Palindrome Number

Java Programs

Problem: Write a Java program to check whether the given number is Palindrome or not.

A Palindrome number is a number that is equal to its reverse. For examples: 11, 121, 77, 2442, etc.

palindrome number

Steps to check Palindrome number in Java:

  1. Input a number.
  2. Reverse the number using a while loop.
  3. Check if the computed reverse is equal to the input number.
  4. If so, then the number is palindrome otherwise not.

Here is the Java program that implements the above steps to check palindrome number:

import java.util.Scanner;
 
public class Palindrome {
 
    public static void main(String args[]){
 
        Scanner in = new Scanner(System.in);
 
        //Take a number as input
        System.out.println("Enter a1 number");
        int num = in.nextInt();
        int temp = num, rev =0;
 
        //Reverse the number
        while(temp>0){
            rev = 10*rev + temp%10;
            temp = temp/10;
        }
 
        //Compare reverse with original
        if(rev == num)
            System.out.println("Palindrome number");
        else
            System.out.println("Not a Palindrome number");
    }
}

Output:

Enter a number
141
Palindrome number

Print all Palindrome Numbers in the Given Interval

To print all palindrome numbers in a given interval, we check each number using the above algorithm.

To do this, we will write the check algorithm in a different function and call the function for each number in the given interval.

import java.util.Scanner;
 
public class Palindrome {
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
 
        System.out.print("Input lower interval value: ");
        int l = in.nextInt();
        System.out.print("Input upper interval value: ");
        int h = in.nextInt();
 
        System.out.println("Palindrome numbers between "+l+" and "+h);
        for(int i=l; i<=h; i++){
            if(checkPalindrome(i))
                System.out.print(i+" ");
        }
    }
 
    public static boolean checkPalindrome(int num){
        int rev=0, temp = num;
 
        //Reverse the number
        while(temp>0){
            rev = 10*rev + temp%10;
            temp = temp/10;
        }
 
        //Compare reverse with original
        return rev == num;
    }
}

Output:

Input lower interval value: 1
Input upper interval value: 100
Palindrome numbers between 1 and 100
1 2 3 4 5 6 7 8 9 11 22 33 44 55 66 77 88 99

In this tutorial, we learned to check palindrome numbers using the Java programming language.

Leave a Reply

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