0 votes
in JAVA by
How to Calculate Palindrome in Java

1 Answer

0 votes
by

next →← prev

Palindrome Program in Java

Palindrome number in java: A palindrome number is a number that is same after reverse. For example 545, 151, 34543, 343, 171, 48984 are the palindrome numbers. It can also be a string like LOL, MADAM etc.

Palindrome number algorithm

Get the number to check for palindrome

Hold the number in temporary variable

Reverse the number

Compare the temporary number with reversed number

If both numbers are same, print "palindrome number"

Else print "not palindrome number"

Let's see the palindrome program in java. In this java program, we will get a number variable and check whether number is 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

Palindrome Program in Java (Another way)

You can also use a method where number or string is not predefined. Here, user has to put the number or string as input to check if the number/string is palindrome.

import java.util.*;   

class PalindromeExample2  

{  

   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:

Use image PalindromeExample

Related questions

0 votes
asked Mar 16, 2021 in JAVA by Robindeniel
0 votes
asked Oct 10, 2020 in JAVA by Robindeniel
...