HomeJavaJava Program to Check Whether a Number is Palindrome or Not

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

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022