Number is Palindrome or Not in Java


This Java program prompts the user to enter an integer and then checks if the entered number is a palindrome or not. Here's how it works:

  • The program prompts the user to enter a number using the Scanner class.
  • The entered number is stored in the integer variable "n".
  • The integer variable "temp" is initialized with the value of "n".
  • A while loop is used to reverse the integer "n" and store the result in the integer variable "reverse".
  • In each iteration of the loop, the remainder of "n" when divided by 10 is stored in the integer variable "rem".
  • The value of "reverse" is then multiplied by 10 and added to "rem", which shifts the digits in "reverse" one place to the left and adds the new digit from "rem" to the units place.
  • The value of "n" is then divided by 10 to remove the units digit.
  • The loop continues until all the digits in "n" have been reversed and stored in "reverse".
  • After the loop, the program checks if the reversed number "reverse" is equal to the original number "temp".
  • If the two numbers are equal, the program prints a message indicating that the number is a palindrome.
  • If the two numbers are not equal, the program prints a message indicating that the number is not a palindrome.

Source Code

import java.util.Scanner;
 
public class number_palindrome {
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter The Number : ");
        int n = in.nextInt();
        int temp=n;
        int reverse=0, rem;
        while(n!=0)
        {
            rem=n%10;
            reverse=reverse*10+rem;
            n/=10;
        }
        if(temp==reverse)
        {
            System.out.println(reverse+" Number is Palindrome");
        }else {
            System.out.println(reverse+" Number is Not a Palindrome");
        }
 
    }
}
 

Output

Enter The Number : 64546
64546 Number is Palindrome
Enter The Number : 4654
4564 Number is Not a Palindrome
To download raw file Click Here

Basic Programs