Java Program for Palindrome Number

Here you will get java program for palindrome number.

A number is said palindrome if its is equal to its reverse. For example, 131 is palindrome while 123 is not.

Below I have shared two ways to check palindrome in java.

Java Program for Palindrome Number

Method 1:

In this method we will reverse the number and then compare it with original number.

import java.util.Scanner;

public class JavaPalindrome {
	public static void main(String args[]){
		int n, m, reverse = 0;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter a number:");
		n = sc.nextInt();
		m = n;
		
		while(m != 0){
			reverse = (reverse * 10) + (m % 10);
			m = m / 10;
		}
		
		if(reverse == n){
			System.out.println("Number is Palindrome");
		}
		else{
			System.out.println("Number is Not Palindrome");
		}			
	}
}

Output

Enter a number:
121
Number is Palindrome

 

Method 2:

In this method we will first convert the number into string and then reverse the string. If reversed string is equal to original then number is palindrome otherwise not.

import java.util.Scanner;

public class JavaPalindrome {
	public static void main(String args[]){
		int n;
		StringBuffer str;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter a number:");
		n = sc.nextInt();
		
		str = new StringBuffer(String.valueOf(n));
		
		if(str.toString().equals(str.reverse().toString())){
			System.out.println("Number is Palindrome");
		}
		else{
			System.out.println("Number is Not Palindrome");
		}
	}
}

Output

Enter a number:
124
Number is Not Palindrome

Leave a Comment

Your email address will not be published. Required fields are marked *