7 July 2020   |   by Marshi Shastri   |   Palindrome, Blogs

Palindrome program in Java

Implementing Palindrome program in Java

In this tutorial, we will learn how to code a palindrome number identifier program in java. Read this tutorial till the end to fully understand this concept.



What is palindrome number?

A number that remains same even after reversing it, is called a palindrome number. Example of some palindrome numbers are 12321, 454, 101, etc. All these numbers will remain same even if we reverse their digits.

Algorithm

1. Take the number to be checked and create a copy of the number, numberCopy. This new variable numberCopy will be used to perform operations in the program, so that our original number remains unaltered.

2. Create new variable reversedNumber to store the number with reversed digits.

3. Create an integer variable digit to store the digit one by one.

4. Iterate over the number stored in numberCopy digit by digit, until the number becomes zero.
   a. Extract last digit from number
   b. Add this digit to the reversedNumber to create a reversed number of numberCopy
   c. Now, divide numberCopy by 10 to reduce one last digit from it.

5. Lastly, when the iteration is over, we will check if the reversedNumber calculated is equal to the original number, number. If yes, then number is a palindrome number else the number is not a palindrome number. Printing the results accordingly.

Java Program

The following is the palindrome program in java. In this program, we have a number in number variable to check whether number is palindrome or not.

public class PalindromeProgram
{
public static void main(String args[])
{

int number = 121;
int numberCopy = number;
int reversedNumber = 0;
int digit = 0;

while(numberCopy != 0)
{
digit = numberCopy % 10;
reversedNumber = reversedNumber * 10 + digit;
numberCopy = numberCopy / 10;
}

if(reversedNumber == number)
System.out.println("Number is a Palindrome number");
else
System.out.println("Number is not a Palindrome number");

}
}

Output

1. When the 'number' has value equal to 121, the program output is shown below:

    Number is a Palindrome number


2. When the 'number' has value equal to 4521, the program output is shown below:

    Number is not a Palindrome number