In this Java program, you’ll learn how to Check Whether a Number is Palindrome or Not using the Java programming language.
Palindrome– Palindrome is a number that gives the same number after reversing that number.
How to Check Whether a Number is Palindrome or Not using JAVA?
Example 1: Java program to check palindrome number
RUN CODE SNIPPETclass Main { public static void main(String[] args) { int num = 6789, reversedNum = 0, remainder; int originalNum = num; while (num != 0) { remainder = num % 10; reversedNum = reversedNum * 10 + remainder; num /= 10; } if (originalNum == reversedNum) { System.out.println(originalNum + " is Palindrome."); } else { System.out.println(originalNum + " is not Palindrome."); } } }
OUTPUT
6789 is not Palindrome.
In the above example, the while loop is used to reverse the number and the result is stored in reversedNum.
To check whether the number is palindrome or not here we use if..else statement.
Example 2: Java program to check palindrome string
RUN CODE SNIPPETclass Main { public static void main(String[] args) { String str = "mom", reverseStr = ""; int strLength = str.length(); for (int i = (strLength - 1); i >=0; --i) { reverseStr = reverseStr + str.charAt(i); } if (str.toLowerCase().equals(reverseStr.toLowerCase())) { System.out.println(str + " is a Palindrome String."); } else { System.out.println(str + " is not a Palindrome String."); } } }
OUTPUT
mom is a Palindrome String.
In the above program, to reverse the number we have used for loop and to check whether the string is palindrome or not we have used if statement.