Java Programs

Palindrome Program using Iteration

We will learn how to write a program in Java to check whether a given number is palindromic or not, using iteration.

Before we start writing the program directly

How will our Java program behave?

Our program will take a number as input to check the given number.

Suppose someone enters the number 121, our program should output: “The given number is a palindrome”.

And if someone enters the number 123, our program should output: “The given number is not a palindrome”.

Program:

import java.util.*;
  
class Main { 

    public static void main(String ...args){

        int tempvar,remainder,reverseNum=0;
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter number- ");  
        int originalNum= sc.nextInt();  
        tempvar = originalNum;

        while (tempvar != 0) {
            remainder = tempvar % 10;
            reverseNum = reverseNum * 10 + remainder;
            tempvar /= 10;
        }

        if (originalNum == reverseNum)
            System.out.print("Number is palindrom");  
        else
	        System.out.print("Number is not palindrom");
    }

}

Output:

Enter number- 232
Number is palindrom

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs