Java Program to Check Whether a Number is Palindrome or Not

In this Java program, you’ll learn how to Check Whether a Number is Palindrome or Not using the Java programming language. 

Palindrome– Palindrome is a number that gives the same number after reversing that number. 

How to Check Whether a Number is Palindrome or Not using JAVA?

Example 1: Java program to check palindrome number 

RUN CODE SNIPPET
class Main { 
  public static void main(String[] args) { 
    int num = 6789, reversedNum = 0, remainder; 
    int originalNum = num; 
    while (num != 0) { 
      remainder = num % 10; 
      reversedNum = reversedNum * 10 + remainder; 
      num /= 10; 
    } 
    if (originalNum == reversedNum) { 
      System.out.println(originalNum + " is Palindrome."); 
    } 
    else { 
      System.out.println(originalNum + " is not Palindrome."); 
    } 
  } 
}

OUTPUT 

6789 is not Palindrome.

In the above example, the while loop is used to reverse the number and the result is stored in reversedNum. 

To check whether the number is palindrome or not here we use if..else statement. 

Example 2: Java program to check palindrome string 

RUN CODE SNIPPET
class Main { 
  public static void main(String[] args) { 
    String str = "mom", reverseStr = ""; 
    int strLength = str.length(); 
    for (int i = (strLength - 1); i >=0; --i) { 
      reverseStr = reverseStr + str.charAt(i); 
    } 
    if (str.toLowerCase().equals(reverseStr.toLowerCase())) { 
      System.out.println(str + " is a Palindrome String."); 
    } 
    else { 
      System.out.println(str + " is not a Palindrome String."); 
    } 
  } 
}

OUTPUT 

mom is a Palindrome String.

In the above program, to reverse the number we have used for loop and to check whether the string is palindrome or not we have used if statement. 

Share:

Leave A Reply

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

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024