Related Tags

communitycreator
java
palindrome

# How to check for Palindrome numbers in Java

Vinisha Maheshwari

A palindrome number is a number that has the same value as that of the original number when reversed, e.g., 121, 111, 1223221. If you were to reverse the number 1223221, the resulting number would also be 1223221.

### Code

The code below shows how to use the iterative method to check for palindrome numbers in Java.

import java.util.Scanner;
class PalindromeCheck {
static int reverseNumber(int n)
{
int reversed_n = 0;
while (n > 0) {
reversed_n = reversed_n * 10 + n % 10;
n = n / 10;
}
return reversed_n;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int reverseN = reverseNumber(n);
if (n == reverseN)
System.out.println(n + " is a Palindrome.");
else
System.out.println(n + " is not a Palindrome.");
}
}

Enter the input below

Check whether a number is Palindrome or not in Java

### Explanation

The code above performs the following actions:

• In line 1 the Scanner class is imported to read inputs from the user.

• In lines 3 to 11 the reverseNumber() function is created, which accepts the number and returns the reversed number. The number is reversed by taking its last digit and multiplying that digit with a factor of 10 every time.

• In lines 14 and 15 an object of the Scanner class is created to read the input from the user.

• Line 16 invokes the reverseNumber() function with the provided number as its parameter.

• Lines 17 to 20 check if the reversed number is equal to the original number i.e., whether the number is a palindrome, and prints a message accordingly.

RELATED TAGS

communitycreator
java
palindrome

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time