Hello Folks,

In this post, we will learn a java program which will check if a given number is palindrome or not.

What is palindrome?

A palindromic number or numeral palindrome is a number that remains the same when its digits are reversed.

For example: 16461.

JAVA Program:

 


import java.util.Scanner;

public class PalindromeNumber {

	public static void main(String[] args) {
		
		// Taking input from user
		Scanner sc= new Scanner(System.in);
		System.out.println("Please give the input number to check palindrome:");
		int inputByUser= sc.nextInt();
		System.out.println("Number to be checked for palindrome: "+inputByUser);
		int temp= inputByUser;
		int revNumber=0;
		// checking if number is negative
		if(inputByUser<0) { System.out.println("Negative number.Enter positive number."); System.exit(1); } // checking if number is single digit only else if(inputByUser>=0 && inputByUser<=9) { System.out.println(inputByUser+" is palindomre as it is single digit number."); System.exit(1); } else { while(temp>0)
			{
			// extracting last digit of number 
			int rem= temp%10;
			// forming number
			revNumber= revNumber*10+rem;
			// removing last digit from number
			temp=temp/10;
			}
			System.out.println("Input By User:"+inputByUser);
			System.out.println("Reverse number:"+revNumber);
			if(inputByUser==revNumber)
			{
				System.out.println(inputByUser+" is a Palindrome Number");
			}
			else
			{
				System.out.println(inputByUser+" is not a Palindrome Number");
			}
			
		}
		
	}
}

Output:
Please give the input number to check palindrome:
-10
Number to be checked for palindrome: -10
Negative number.Enter positive number.

Please give the input number to check palindrome:
5
Number to be checked for palindrome: 5
5 is palindrome as it is single digit number.

Please give the input number to check palindrome:
16461
Number to be checked for palindrome: 16461
Input By User:16461
Reverse number:16461
16461 is a Palindrome Number

Please give the input number to check palindrome:
87342
Number to be checked for palindrome: 87342
Input By User:87342
Reverse number:24378
87342 is not a Palindrome Number

You can run above program for multiple inputs and if it fails for any condition, let me know.

#HappyCoding

One thought on “Java program To Check If a given number is Palindrome.

Leave a Reply