Java Programs

Palindrome Program using Recursion

In this tutorial you will learn how to write a program in Java to check whether a given number is palindromic or not, using recursion.

Before we proceed directly to writing the program to check whether a given number is palindromic or not by using recursion

How will this Java program behave?

This palindrome program takes an integer as input. After applying some operations written in the program, the output will be printed.

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

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

Program:

import java.util.*;  

class Main {

    static int sum=0,rem;
    static int isPalindrome(int num)
    {
        if(num == reverse(num))
        {
            return 1;
        }
        return 0;
    }

    static int reverse(int num){
       if(num!=0){
            rem=num%10;
            sum=sum*10+rem;
            reverse(num/10);
        }
        else
            return sum;
        return sum;
    }

    public static void main(String ...args){
        int result;
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter number- ");  
        int originalNum= sc.nextInt();  
        result = isPalindrome(originalNum);
        if(result == 1){
            System.out.println("number is a palindrome");
        }else{
            System.out.println("number is not a palindrome");
        }
    }

} 

Output:

Enter number- 232
number is a palindrome

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs