Check Palindrome Number in Java

Check whether a number is a palindrome (same forwards and backwards).

BeginnerModule 2: Conditional ProgramsExample 8 of 20
check-palindrome-number.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6
7 System.out.print("Enter a number: ");
8 int n = sc.nextInt();
9
10 int temp = n;
11 int rev = 0;
12 while (temp != 0) {
13 int d = temp % 10;
14 rev = rev * 10 + d;
15 temp /= 10;
16 }
17
18 if (rev == n) {
19 System.out.println(n + " is a Palindrome Number");
20 } else {
21 System.out.println(n + " is not a Palindrome Number");
22 }
23
24 sc.close();
25 }
26}

Output

Enter a number: 121
121 is a Palindrome Number

What's going on

We reverse the digits and compare with the original number.