How to
find if a number is a palindrome in Java
Checking whether a number is palindrome or not is a classical Java
homework exercise. When you start learning Java programming most institute
which teaches Java programming provides
these classical Java programs like How
to find Armstrong number in Java or how
to find the Fibonacci number in Java using recursion etc. Write a Java program to check if the number is palindrome comes from the same category. For those who are not familiar with
palindrome numbers, a palindrome number is a number that is equal to the reverse of
itself.
For example, 121 is a palindrome because the reverse of 121 is 121, while
123 is not a palindrome in Java because the reverse of 123 is 321 and 121!=321. Finding a palindrome number is easy in Java, you just need to develop logic
to reverse a number in Java.
Thankfully Java provides a couple of arithmetic operators like remainder(%) operator also known as modules operator, which returns remainder in division operator and division operator(/) which returns quotient. By using remainder and division operator in Java we can create program to check if the number is palindrome or not.
Thankfully Java provides a couple of arithmetic operators like remainder(%) operator also known as modules operator, which returns remainder in division operator and division operator(/) which returns quotient. By using remainder and division operator in Java we can create program to check if the number is palindrome or not.
Java program – palindrome numbers in Java
Here is a complete Java program to check if a given number is palindrome
or not, This program works for both positive and negative numbers and displays
if it's palindrome irrespective of their sign. Any one-digit number including
zero is always palindrome.
This program is able to check two-digit, three-digit numbers for a palindrome and effectively go to any number in Java.
Let’s see
how to write a Java program to find palindrome numbers :
package testing;
import java.util.Scanner;
import java.util.Scanner;
/**
* Java program to check if the number is palindrome or not.
* A number is called palindrome if the number
* and its reverse is equal
* This Java program can also be used to reverse a number in Java
*/
public class NoClassDefFoundErrorDueToStaticInitFailure {
public static void main(String args[]){
System.out.println("Please Enter a number : ");
int palindrome = new Scanner(System.in).nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number : " + palindrome
+ " is a palindrome");
}else{
System.out.println("Number : " + palindrome
+ " is not a palindrome");
}
}
/*
* Java method to check if a number is palindrome or not
*/
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and the reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
}
Output:
Please Enter a number :
123
Number: 123 is not a palindrome
Please Enter a number :
121
Number: 123 is a palindrome
* Java program to check if the number is palindrome or not.
* A number is called palindrome if the number
* and its reverse is equal
* This Java program can also be used to reverse a number in Java
*/
public class NoClassDefFoundErrorDueToStaticInitFailure {
public static void main(String args[]){
System.out.println("Please Enter a number : ");
int palindrome = new Scanner(System.in).nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number : " + palindrome
+ " is a palindrome");
}else{
System.out.println("Number : " + palindrome
+ " is not a palindrome");
}
}
/*
* Java method to check if a number is palindrome or not
*/
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and the reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
}
Output:
Please Enter a number :
123
Number: 123 is not a palindrome
Please Enter a number :
121
Number: 123 is a palindrome
That’s all on how to check if a number is a palindrome or not in Java.
If you are looking for the answer to this question for interview purposes then better
prepare a recursive version of the palindrome program in Java as well because of its
common practice that programmer is expected to write java programs using both
recursion and iteration in Java. Let me know if you find any other way of
checking palindrome in Java.
Other Java homework programming exercises:
- How to reverse String in Java without using API
- Write a Java program to find factorial of a number using recursion
- Write a Java program to print prime numbers in Java
- Write a Java program to find the IP address of localhost in Java
- Top 10 Java coding interview questions and answers
Also, what is your favorite Java programming exercise? Prime Number, Fibonacci series, Binary Search, or this one? Do let me know in comments.
Very good Program!
ReplyDeletePlease correct the out put when it asks 121 is a palindrome....the result says
123" is a palindrome... it should be 121 :)
Cheers!
Hi, Thanks for this. The program is working well but I am trying to understand how the reverse(sort of where it came from) fits the program.
ReplyDelete// Variations, using charAt
ReplyDeletepublic static boolean isPolindrome(int n) {
String s = String.valueOf(n).toString();
String rs = new StringBuffer(s).reverse().toString();
for (int i=0; i<s.length(); i++) {
if (s.charAt(i) != rs.charAt(i)) return false;
}
return true;
}
Hi you dont even need to reverse the string .
ReplyDeletestatic boolean checkAlgoOne(int num) {
boolean check = false;
String number = Integer.toString(num);
char[] chars = number.toCharArray();
int len = chars.length;
if (num < 0)
check = false;
if (num == 0 || num == 1)
check = true;
if (len % 2 != 1) {
check = false;
} else {
for (int i = 0; i <= len / 2; i++) {
if (chars[i] == chars[len - 1])
check = true;
}
}
return check;
}
cheers!
1221 is palindrome, but your program will say it's not
Deleteimport java.util.Scanner;
Deletepublic class integerpolindrome {
public static void main(String[] args) {
int poly=0;
System.out.println("enter the integr number :");//123
int num= new Scanner(System.in).nextInt();
int real=num;
while(num!=0)
{
int rem=num%10;//3
poly =rem+10*poly;
num/=10;
}
if(poly==real)
{
System.out.println("its a polindrome number:");
}
else
System.out.println("its not a polindrome number:");
}
}
//try this one
My way:
ReplyDelete/* Palindrome Program In JAVA
© Code Nirvana (www.codenirvana.in)
*/
import java.util.Scanner;
class Palindrome{
public static void main(String args[]){
System.out.print("Enter Number: ");
Scanner read = new Scanner(System.in);
int num = read.nextInt();
int n = num;
//reversing number
int rev=0,rmd;
while(num > 0)
{
rmd = num % 10;
rev = rev * 10 + rmd;
num = num / 10;
}
if(rev == n)
System.out.println(n+" is a Palindrome Number!");
else
System.out.println(n+" is not a Palindrome Number!");
}
}
MORE @ http://www.codenirvana.in/2013/10/Palindrome-Number-in-JAVA.html
hi,
Deletecan u explain why you have divided input by 10 and and %10 for reversing a number series...please explain that part.
Hello @Anonymous, when you divide the number you drop last digit from number and when you to module 10 i.. % 10 you get the last digit of the number.
DeleteFor example, 123/10 = 12, last digit 3 is gone so number reduced from 3 to 2
123%10 = 3 means last digit.
This is the trick you need to reverse the number.
why do we have 121/10=12 instead of 12.1
Deletewhy do we have 121/10 as 12 instead of 12.1
DeleteYou've probably figured this out by now but I will write the answer anyway in case someone else stumbles upon this thread.
DeleteThe answer is simple - because it's an integer, and integers are whole numbers. For the number to store 12.1 it would have to be a double or a float, both of which allow fractions.
private static boolean isPalindrome(int n) {
ReplyDeletereturn n == Integer.valueOf(new StringBuilder(String.valueOf(n)).reverse().toString());
}
private void checkPolyndrom(String st) {
ReplyDeleteboolean polyn=true;
for(int i =0; i<st.length()-1/2; i++){
if(st.charAt(i)==st.charAt(st.length()-1-i) && polyn){
polyn=true;
}else{
polyn=false;
}
}
if(polyn){
System.out.println("Polyndrom");
}else{
System.out.println("Not Polyndrom");
}
}
Why do we multiply rev*10+ remainder
ReplyDeleteto reverse
Deleteall are from which standards
ReplyDeleteIs 1221 a palindrome number. ????
ReplyDeleteyes
Deletepublic static boolean isPalindrome(int n) {
ReplyDeleteString i = Integer.toString(n);
int first = 0;
int last = i.length() - 1;
while (first < last) {
if (i.charAt(first) == i.charAt(last)) {
first++;
last--;
} else {
return false;
}
}
return true;
}
good examples and thanks to all..
ReplyDeletehow to close the scanner int function?? for resolving warning.
ReplyDelete(Scanner name).close();
DeletemyScanner.close();
Deletetry this simple way
ReplyDeleteimport java.util.*;
class StringPalindrome
{
public static void main (String ar[])
{
String a, b;
StringBuffer sb;
Scanner sc=new Scanner (System.in);
System.out.println("Ente rhe string");
a=sc.nextLine();
sb=new StringBuffer(a);
b=sb.reverse().toString();
if(a.equals(b))
{
System.out.println("The string is palidrome");
}
else
{
System.out.println("The string is not a palindrome");
}}}
public static boolean isNumberPalindrome(int str) {
ReplyDeletereturn str == Integer.parseInt(new StringBuilder().append(str).reverse().toString());
}
Palindrome Check using HashSet:
ReplyDeleteimport java.util.HashSet;
import java.util.Set;
public class p16 {
public static void main(String[] args) {
String a = "malayalam1";
System.out.println(ispalindrome(a));
}
private static boolean ispalindrome(String a) {
Set set = new HashSet<>();
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
if(set.contains(ch)) {
set.remove(ch);
}else {
set.add(ch);
}
}
return set.size() <= 1 ;
}
}
Integer i = 1221;
ReplyDeletechar word[] = i.toString().toCharArray();
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
System.out.println("not palindrome");
break;
}
++i1;
--i2;
}
if(i==s.length()%2)
ReplyDelete{
System.out.println("Palidrome");
}
public class NumberPalindrome {
ReplyDeletepublic static boolean isPalindrome(int number)
{
int rem=0,reverse=0,start=number;
while(number!=0)
{
rem=number%10;
reverse=(reverse*10) +rem;
System.out.println("rev= "+reverse);
number=number/10;
}
if(reverse==start)
return true;
return false;
}
}
It is harder to understand with numbers than with string.
ReplyDeleteYeah, you need to know how to get the last digit of an number (remainder of divide by 10) and how to reduce 3 digit to 2 digit (divide by 10). If you don't know this trick then its a difficult problem to solve.
DeleteThis program fails for numbers starting with a 0...Please correct your code..
ReplyDeletenumber starting with zero? that's not the valid number, how do you distinguish between 10 and 010? unless you are using string.
Deletepublic class Palanadrone {
ReplyDeletepublic static void main(String[] args)
{
//////////// for integer
int a=1551;
if(String.valueOf(a).equals(new StringBuffer(String.valueOf(a)).reverse().toString()))
System.out.println("the number is palandrone");
else
System.out.println("the number is not palandrone");
/////////// for string
String s4="teet";
if(s4.equals(new StringBuilder(s4).reverse().toString()))
System.out.println("the string is palandrone");
else
System.out.println("the string is not palandrone");
}
}
That's cool but in interview you may not be allowed to use the reverse() method, Can you solve this problem without using StringBuffer or StringBuilder and reverse method?
Deletepackage javaapplication6;
ReplyDeleteimport java.util.Scanner;
/**
*
* @author MANISHA
*/
public class JavaApplication6 {
/**
* Java program to check if the number is palindrome or not.
* A number is called palindrome if the number and its reverse is equal
* This Java program can also be used to reverse a number in Java
*/
public static void main(String args[]){
System.out.println("Please Enter a number : ");
Scanner console = new Scanner(System.in);
int palindrome=console.nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number is a palindrome");
}
else
{
System.out.println("Number is not a palindrome");
}
}
/*
* Java method to check if a number is palindrome or not
*/
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
}