Categories: softare development

Check If a Number is Palindrome in Java

It is true that Strings can be palindromic in nature. The same can equally be said of numbers.

A palindromic number (sometimes called numeral or numeric palindrome) is one such that if its digits are reversed, it stays the same.

This number is said to have a reflectional symmetry across the vertical axis. Example of such numbers are 16461, 151, 242, etc.

Let us now see how we can check for this palindromic quality using Java programming language.

class CheckPalindrome{

public static void main(Strings args[]){
  System.out.println(isPalindromeInt(121));
}

public static String isPalindromeInt(int n) {
   
   int reversedNum = 0;
   int remainder;
   int originalNum = n;
    
         while (n != 0) {
      remainder = num % 10;
      reversedNum = reversedNum * 10 + remainder;
      n /= 10;
    }
    
    // check if reversedNum and originalNum are equal
    if (originalNum == reversedNum) {
 return originalNum + "is Palindrome.";
    }
    else {
    return originalNum + "is not Palindrome.";
    }
  }

}

So what we did here was to create a static method that will return our given result based on the parameters passed.

By using the modulus operator, we effectively get the remainder when we divide by 10 and then attempt to do a reversal.

If the reversed number is still equal to the reversed number, then it is a palindrome, otherwise it is not.

This is effectively how Palindrome works.

Let us know what you think in the comments.

Recent Posts

Recursion for Beginners

Recursion is a programming technique where a function calls itself to solve smaller instances of…

2 days ago

Optional Chaining (?.): How to Avoid ‘Cannot Read Property’ Errors in JavaScript

One of the most common errors in JavaScript is the dreaded TypeError: Cannot read property…

4 days ago

ReferenceError vs. TypeError: What’s the Difference?

When debugging JavaScript, you’ll often encounter ReferenceError and TypeError. While both indicate something went wrong,…

6 days ago

document.querySelector() vs. getElementById(): Which is Faster?

When selecting DOM elements in JavaScript, two common methods are document.querySelector() and document.getElementById(). But which…

6 days ago

npm vs. Yarn: Which Package Manager Should You Use in 2025?

When starting a JavaScript project, one of the first decisions you’ll face is: Should I…

1 week ago

Why Learn Software Development? (And Where to Start)

Software development is one of the most valuable skills you can learn. From building websites…

2 weeks ago