Check if Number is Palindrome or Not

A number can be a palindrome if number itself is equal to reverse of number, for example 121 is a palindrome because reverse of this number is also 121, but on the other hand 123 is not a palindrome because reverse of 123 is 321 which is not equal to 123, i.e. original number. To check a given number is palindrome or not we can use different logic’s like we can reverse the number and then compare the original number with reverse number.
other logic can be to convert the number to String and then reverse the string using StringBuilder or StringBuffer reverse() method, compare the String and then convert back it to number

Program to check Number is Palindrome or not
import java.util.Scanner;

public class Palindrome {
  
  
    public static void main(String args[]){
      
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Please enter a number");
        
        int number = sc.nextInt();
              
        sc.close();
        
        boolean status = isPalindrome(number);
        
    	if(status == true){
    		System.out.println("Number is Palindrome");
    		}
    		else{
    		System.out.println("Number is not Palindrome");
    		}
    }

    private static boolean isPalindrome(int number) {
        if(number == reverse(number)){
            return true;
        }
        return false;
    }
  
      
    private static int reverse(int number){
        int reverse = 0;
      
        while(number != 0){
          reverse = reverse*10 + number%10; 
          number = number/10;
        }
              
        return reverse;
    }

}

in the above method we are taking Integer type input from the console.
Passing the input to the isPalindrome() Method reverse the number, compare the original with reverse and then return the status true or false on the basis of condition that if original is equal to reverse, it means that it is palindrome number return true else return false and then Print the number is palindrome or not.
Program Output :

Please enter a number:
121
Number is Palindrome

Please enter a number:
123
Number is not Palindrome

Leave a Comment