In this Java Program, you will learn how to check whether a given number is a palindrome or not.
A palindrome is a word, number, phrase, or other sequence of characters that reads the same backward as forward, such as civic or rotator or the number 14241.
A number is a palindrome when we reverse the number and the reversed number is equal to the original number.
Here is the code of the program to check whether a given number is a palindrome or not.
In this program, you will see how to Check Whether a Number is Palindrome or Not using While Loop.
//Java Program to Check Whether a Number is Palindrome or Not
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int num, reversedNum = 0, remainder;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number: ");
num = sc.nextInt();
// closing scanner class(not compulsory, but good programming practice)
sc.close();
// store the number to originalNum
int originalNum = num;
// get the reverse of originalNum
// store it in variable
while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
// check if reversedNum and originalNum are equal
if (originalNum == reversedNum) {
System.out.println(originalNum + " is Palindrome.");
} else {
System.out.println(originalNum + " is not Palindrome.");
}
}
}
Enter a Number:
5445
5445 is Palindrome.
Enter a Number:
65895
65895 is not Palindrome.
Here in the above program, we have used the
while
loop to reverse num and store the reversed number in reversedNum
if...else
to check if reversedNum
is the same as the originalNum
In this program, you will see how to Check Whether a Number is Palindrome or Not using For Loop.
//Java Program to Check Whether a Number is Palindrome or Not Using For Loop
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int num, reversedNum = 0, remainder;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number: ");
num = sc.nextInt();
// closing scanner class(not compulsory, but good programming practice)
sc.close();
// store the number to originalNum
int originalNum = num;
// reversed integer is stored in variable
for (; num != 0; num /= 10) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
}
// check if reversedNum and originalNum are equal
if (originalNum == reversedNum) {
System.out.println(originalNum + " is Palindrome.");
} else {
System.out.println(originalNum + " is not Palindrome.");
}
}
}
Enter a Number:
856
856 is not Palindrome.
Enter a Number:
646
646 is Palindrome.
Here in the above program, we have used the
For
loop to reverse num
and store the reversed number in reversedNum
if...else
to check if reversedNum
is the same as the originalNum
Comments