Palindrome Number in JAVA

Hey there! Welcome to another programming post here on Geekstocode! In this post, we are going to discuss Palindrome Numbers in Java. Java program for a palindrome number. We can interpret this program in many forms. In this post we are basically going to see two of its forms.

It will help you analyze the basic java concepts more clearly. Also, it will help you in your coding exams. This program is also a very beginner-level JAVA code. Thus, they can also ask this as an interview question. Therefore, you need to be properly prepared for this one.

Read about Punctuators and Separators in Java

Hence, without much delay, let’s get our coding brains to use and get started! 

What is a palindrome?

Because we are working with a palindrome number, it is necessary that you know what exactly is a palindrome number. Don’t worry we got you covered. We will give you the proper explanation of what it is exactly. 

The word “palindrome” originates from ancient Greece. It is a word, number, or set of characters that reads the same forward and backwards. For example, MOM, 141, 21000012, etc.

In other words, we can define a palindrome as a word or a number or a set of characters which will have the same spelling even if it is reversed. 

Now, there are two kinds of palindromes, a word or a number. Besides, it can also be a phrase.

Palindrome Number : It is a number that remains the same even after we reverse its order. For instance, 222, 1001, 676, etc. 

Palindrome Word : It is a word or a phrase that is spelled the same even in the backward direction. But, we ignore spacing, punctuations, and capitalization.

For example:

  • racecar
  • tenet
  • rotor
  • Madam

To explain it further, let us consider the number 161. Here if you read it backwards, it will still be 161. Therefore, it is a palindrome number.

Similarly, if we take the word, rotor. Try reversing it. Yes, it will still read rotor. Thus, it is the same without any difference even if we read from front or back. Hence, it is a palindrome word. 

Palindrome programs in JAVA: 

In JAVA, we can approach the palindrome number program in different methods. Thus, we have put together three of these methods for your ease of understanding. This way you will be having three ways in hand to learn the concept of palindrome number.

Hence, you will be ready for any of the questions they ask whether it is in college or in your interview. In these methods, we will approach the problem using the two major loops, for and while. Also the third method will be using the string method.

Therefore we are assuming that you are already thorough about the various loops in JAVA.

Now that you know all the methods and their overview, let us jump right to the programs. 

Program to find if the number is palindrome using a while loop. 

Algorithm:

  1. Start
  2. Declare the class Main
  3. Then, declare the public main function.
  4. Declare r, sum as 0 and flag integer variables for storing the remainder, sum/ reverse of the number and the temporary number respectively. 
  5. After that, initialize the integer n with the number you want to check. 
  6. Initialize the flag with n so that it stores the number. Because in the process our original number might get lost. 
  7. Then, move on to the while loop with the condition n>0 or n not equal to 0.
  8. Get the remainder r by n mod 10.
  9. Now, calculate the sum by the formula sum = ( sum x 10 ) + r.
  10. Then, reduce the number n by one digit, i.e n/10.
  11. When the while loop completes all its conditions, compiler will move out of the loop. 
  12. Next, move to the if condition. 
  13. If the flag is equal to the new reverse number or sum, we print the number as palindrome.
  14. And if the condition is false, we print the number as not palindrome.
  15. Stop. 

Program:

//JAVA Program to check for palindrome number
public class Main
{
	public static void main(String[] args) {
		 
  int r,sum=0,flag;    
  int n=161;//It is the number variable to be checked for palindrome  
  
  flag=n;    
  while(n>0){    
   r=n%10;  //getting remainder  
   sum=(sum*10)+r;    
   n=n/10;    
  }    
  if(flag==sum)    
   System.out.println("Entered number is a palindrome number ");    
  else    
   System.out.println("Entered number is not palindrome");    
}  


}

Program Explanation:

In the above set of codes, we have used the while loop to calculate the reverse number. The while loop iteratively checks if the digits in the input until it becomes zero.

Then, inside the loop, we take the modulus of the number.

After that we store it in a variable sum for every  iteration to obtain the exact reverse of the input.

Lastly, we compare the original number to the reversed number stored in sum. Hence, we conclude if the number is palindrome or not. 

Let us take the example of the number 161, and follow step by step with the calculation. 

r = n%10161 % 10 = 116 % 10 = 61 % 10 = 1
sum = (sum * 10) + r(0 * 10) + 1 = 1(1 * 10) + 6 = 16(16 * 10) + 1 = 161
n = n / 10161 / 10 = 1616 /10 = 11 / 10 = 0
num>016> 0  [continue]1 > 0 [continue]0 = 0 [stop]
Calculation for checking the palindrome number in JAVA.

Output:

The program we just executed gives the following output:

Output of Program for checking if the number is Palindrome or not in JAVA
Output of Program for checking if the number is Palindrome or not in JAVA

You can take a non palindrome number for initializing n and check for yourself. The message will change.

Program to find if the number is palindrome using strings.

In the previous program, you have learned about how we check the palindrome number using the while loop. Well, in this method we will use the for loop. Also, we will be taking input from the user to increase its user friendly behavior. 

Algorithm:

  1. Start.
  2. Declare the public main class just like the previous program. 
  3. Then, declare the public void main function with one string parameter.
  4. After that, declare two string objects, original and reverse. The original is for the user entered string and the reverse one will have the reverse string.
  5. Now, ask the user to enter either a string or a number. Since, we can take both inputs, we can check for both type of palindromes. 
  6. Take user input using the nextLine() function.
  7. Next, declare the length integer variable to store the length of the string user has entered.
  8. Then the for loop starts.
  9. Initialize i, the counter to the length of the string.
  10. The loop will go on till i is greater than or equal to 0.
  11. Decrement the value of i with each iteration.
  12. After that, in the loop, calculate reverse by the formula reverse = reverse + original.charAt(i).
  13. Then, when the compiler comes out of the loop, move on to the if else block.
  14. In the block, if the original is equal to the reverse, then the string is palindrome or its not.
  15. Thus, print the result accordingly. 
  16. Stop. 

Program:

//JAVA Program to check for palindrome number using the string method.
import java.util.*;  
public class Main
{
  
   public static void main(String args[])  
   {  
      String original, reverse = ""; // Objects of String class  
      Scanner in = new Scanner(System.in);   
      System.out.println("Enter a string/number to check if it is a palindrome");  
      original = in.nextLine();   
      int length = original.length();   
      for ( int i = length - 1; i >= 0; i-- )  
         reverse = reverse + original.charAt(i);  
      if (original.equals(reverse))  
         System.out.println("Entered string/number is a palindrome.");  
      else  
         System.out.println("Entered string/number isn't a palindrome.");   
   }  


}


Program Explanation:

After reading the detailed explanation, you will find the program easy. 

First, we have declared the class and function in JAVA. 

Then, we declare two variables of string class to store the user entered value and the reverse respectively.

Next, we use the nextLine() function to take the user input.

Then, we have initialized a length variable with the length of the user input. 

The most important part is next, i.e the for loop.

In the for loop, we have initialized the counter i with the length of the value that the user has entered. Then, we iterate the loop until the counter reaches the end of the string or the value. 

After that, we have calculated the reverse of the value using the character method formula.

Now, we have both user input value and the reversed value.

Next, we follow the similar procedure of the previous code to check if the reversed value is equal to the original value. 

Then, we print the result accordingly.

The step by step procedure will be the same as the previous method. However, here the compiler will treat the input as a string and the digits as characters. Hence, we don’t have to declare another temporary variable. Because, we will still have the original value with us. 

Output:

The program we just executed gives the following output:

Output for the program checking palindrome using the string method in JAVA
Output for the program checking palindrome using the string method in JAVA

You can also use this program for checking a palindrome string or word.

Modifications:

There can be many modifications in these programs. Make sure to try them out and improve your skills!

  1. Use the for loop and numerical method to check for the palindrome number.
  2. You can also use recursion for checking the palindrome strings.
  3. Next, you can modify the program and make it more efficient using the library functions available in the JAVA library.

Ending note :

Thus, we are now at the end of another coding article. In this post, you have learned about one of the basic programming questions in JAVA, Which is the palindrome number in Java. We have covered two basic methods of solving this coding question.

But we have also mentioned a few modifications which you can try for yourself. Make sure to practice them!

Additionally, we have provided a detailed step by step algorithm and explanation of the code for better understanding. Now, you need to be thorough with this programming question. Because it is beginner level and they often ask you this in school, college or interview. 

Hope this post was helpful. 

Still have doubts or queries? Just ask away. We are here to help.

See you in our next post!

Leave a Comment

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