×

Palindrome number program in Java

Write java program to check if a number is palindrome in Java?

A number that does not change on reversing is called a palindrome number. In other words, when reversing the digits of a number does not affect the number is called the palindrome number. For example, 121, 343, 555, 606, 999, 1001, 1331 are the palindrome numbers. In this section, we will create a Java program to check the number is palindrome or not.

Algorithm to Find Palindrome Number

  • Get the number, which is going to be checked for palindrome.
  • Create a copy of the number by storing it in some temporary variable.
  • Now, reverse the number.
  • Check with the copy whether the reversed number is equal or not.
  • If it is equal, then we have a palindrome number.
  • Otherwise, the number is not a palindrome.

The following Java program demonstrates how to check a given number is a palindrome number or not by using a while loop.

Iterative Approach

Filename: PalindromeNumberExample.java

public class PalindromeNumberExample
{             
public static void main(String[] args)
{
               int no = 535; // To be checked for palindorme
               int tempVar = no; // Creating the copy of ‘no’
               int sum = 0;
               while(no > 0)
               {
                               // reversing the number
                               sum = sum * 10;
                               sum = sum + (no % 10);
                               no = no / 10;
               }
               if(tempVar == sum)
                               System.out.print("The number " + tempVar +" is a palindrome number.");
               else
                               System.out.print("The number " + tempVar +" is not a palindrome number.");
}
}

Output:

The number 535 is a palindrome number.

Explanation: We have used a Java while loop to reverse the number. The number of iterations of the while loop depends on the number of digits present in the given number. In our case, it is 3. Let’s see the working of the program.

First Iteration: sum = sum * 10. However, we have initialized the value of sum as 0; Therefore, we get sum = 0 * 10 = 0. Again, we update the value of sum by adding the remainder we get by dividing the given number (535). Thus, we get sum = 0 + (535 % 10). sum = 0 + 5 = 5. Finally, we divide the given number by 10 and assign the quotient to the number. no = 535 / 10 = 53. The updated value of no variable is 53 which is to be used in the next iteration.

Second Iteration: In the second iteration, the value of sum is 5. Hence, sum = 5 * 10 = 50. Again, we add the remainder. This time the number is 53. Hence, we have sum = 50 + (53 % 10). sum becomes 50 + 3 = 53. At last, the given number shrink again by one digit and becomes 5. no = 53 / 10 = 5.

Third Iteration: The process is similar. The sum is 53. Therefore, sum = 53 * 10 = 530. After adding the remainder, we get 535. Also, the number becomes no = 5/10 = 0. Since every time we have checked the while loop condition. When the condition no>0 returns false, the loop terminates.

Recursive Approach

We can also check the palindrome number by using the recursive approach.

Filename: PalindromeNumberExample1.java

public class PalindromeNumberExample1
{
static boolean isPalindrome(int no, int tempVar, int sum)
{
               if(no < 0) return false;
               if(no == 0) return sum == tempVar;
               return isPalindrome(no/10, tempVar, sum * 10 + (no%10));                  
}
public static void main(String[] args)
{
               int a[] = {4, 434, 909, 100, -66, 123, 797};
               for(int i = 0; i < a.length; i++)
                               if(isPalindrome(a[i], a[i], 0))
                                              System.out.println("The number " + a[i] +" is a palindrome number.");
                               else
                                              System.out.println("The number " + a[i] +" is not a palindrome number.");
}
}

Output:

The number 4 is a palindrome number.
The number 434 is a palindrome number.
The number 909 is a palindrome number.
The number 100 is not a palindrome number.
The number -66 is not a palindrome number.
The number 123 is not a palindrome number.
The number 797 is a palindrome number.

Explanation: In the recursive approach also, we have created a copy of the number and then compared it with the number that we have reversed. Note that as per mathematical definition, a negative number can never be a palindromic number.


Related Topics

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.