Palindrome Program in Java

In Java, a palindrome number refers to a number that remains the same when its digits are reversed. For instance, numbers such as 545, 151, 34543, 343, 171, and 48984 are considered palindrome numbers. Additionally, palindromes can also exist as strings, such as “LOL” or “MADAM”. The defining characteristic of a palindrome is that it retains its original form when read in reverse.

Palindrome Number Algorithm

To check if a number is a palindrome in Java, follow these steps:

  • Obtain the number to be checked for palindrome.
  • Store the number in a temporary variable.
  • Reverse the number.
  • Compare the temporary number with the reversed number.
  • If both numbers are identical, display “palindrome number”.
  • If the numbers differ, display “not palindrome number”.

By applying these steps, you can determine whether a given number is a palindrome or not.

Example 1:

Let’s take a look at a Java program to check whether a given number is a palindrome or not. In this program, we will prompt the user to input a number, store it in a variable, and then verify if the number is a palindrome or not.

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

Output:

palindrome number

Example 2:
Alternatively, you can implement a method that accepts a number or string as input from the user to determine if it is a palindrome. In this approach, the program prompts the user to provide the desired number or string and then checks whether it meets the criteria for being a palindrome.

import java.util.*;   
class PalindromeExample1  
{  
   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.");   
   }  
}

Output:

Enter a string/number to check if it is a palindrome
111
Entered string/number is a palindrome.

For further understanding of concepts such as the Java Palindrome Program, you can refer to the website tutorials.freshersnow.com.