How to Check a Palindrome Number in Java

Learn how to check a palindrome Number in Java using a simple while loop method. This step-by-step guide explains the logic in detail with code examples, potential pitfalls, and best practices. Perfect for beginners!

Introduction

Have you ever come across a number and wondered if it reads the same backward as forward? Well, that’s what we call a palindrome. Whether it’s 121, 1331, or even a word like madam, palindromes have a unique symmetry.

In this blog post, we will learn how to check if a number is a palindrome in Java using a basic method involving a while loop. This approach will be beginner-friendly, easy to understand, and perfect for those starting their journey in coding. Let’s dive in!

What is a Palindrome?

A palindrome is a number or word that reads the same forward and backward. For example, the number 121 is a palindrome because when reversed, it’s still 121. Similarly, 1331 is also a palindrome.

When working with numbers in Java, we can check if a number is a palindrome by reversing the digits and comparing it with the original number. If both are equal, it’s a palindrome!

Now, let’s see how we can implement this in Java using a simple while loop.

The Basic Method – How to Check if a Number is a Palindrome in Java

We will use the following steps to solve this problem:

  1. Reverse the number by extracting its digits one by one.
  2. Compare the reversed number with the original number.
  3. If both are the same, the number is a palindrome.

Let’s break down the code and explain each line in detail.

Java Code to Check if a Number is a Palindrome

public class PalindromeCheck {
    public static void main(String[] args) {
        int num = 121; // Step 1: Define the number to check
        int originalNum = num; // Step 2: Store the original number
        int reversedNum = 0; // Step 3: Initialize reversed number

        // Step 4: Use a while loop to reverse the number
        while (num != 0) {
            int digit = num % 10; // Get the last digit
            reversedNum = reversedNum * 10 + digit; // Add the digit to reversedNum
            num /= 10; // Remove the last digit from num
        }

        // Step 5: Check if reversedNum is equal to originalNum
        if (originalNum == reversedNum) {
            System.out.println(originalNum + " is a palindrome.");
        } else {
            System.out.println(originalNum + " is not a palindrome.");
        }
    }
}

Explanation of Each Step

Let’s break this code down, step by step, and understand what each line is doing:

Step 1: Define the number to check

int num = 121;

Here, we start by defining a variable num which holds the number we want to check. In this case, it’s 121.

Step 2: Store the original number

int originalNum = num;

Since we’ll be modifying num to reverse it, we need to store the original number in a variable called originalNum for comparison later.

Step 3: Initialize reversedNum

int reversedNum = 0;

This is where we will store the reversed number. Initially, it’s set to 0.

Step 4: Reverse the number using a while loop

while (num != 0) {

int digit = num % 10; // Get the last digit

reversedNum = reversedNum * 10 + digit; // Add the digit to reversedNum

num /= 10; // Remove the last digit from num

}

This is where the real action happens:

  • Extracting the last digit:
    • The line num % 10 gives us the last digit of the number. For example, for 121, this gives 1.
  • Building the reversed number:
    • We take this last digit and add it to reversedNum, which shifts any previously stored digits left by multiplying by 10.
    • Initially, reversedNum = 0. After the first iteration, it becomes 1. After the second iteration, it becomes 12, and finally, it becomes 121.
  • Removing the last digit from the original number:
    • The line num /= 10 removes the last digit from num. For example, 121 / 10 results in 12, and then 1 after the next iteration.

Step 5: Compare the reversed number with the original

if (originalNum == reversedNum) {
    System.out.println(originalNum + " is a palindrome.");
} else {
    System.out.println(originalNum + " is not a palindrome.");
}

Finally, we compare originalNum with reversedNum. If they are the same, we print that the number is a palindrome. Otherwise, it’s not.

Why This Method Works

The method works by gradually peeling off the last digit of the original number and adding it to the reversed number. The while loop ensures that the process continues until there are no more digits left in the original number (num == 0).

The key part is understanding the modulus operator (%) and integer division (/). The modulus operator helps us get the last digit, while integer division removes that digit from the original number. This makes it easy to reverse the number, one digit at a time.

Potential Issues and Edge Cases to Watch Out For

While the code works well in most cases, there are a few edge cases and potential pitfalls you should be aware of:

1. Negative Numbers

  • Problem: Negative numbers (e.g., -121) are treated as not palindromes because the sign is not considered.
  • Result: Negative numbers will always return false in this code, even if the absolute value of the number could be a palindrome.
  • Solution: If you want to ignore the negative sign and check the number, you can add this condition:
if (num < 0) {
    System.out.println(originalNum + " is not a palindrome.");
    return;
}

2. Integer Overflow

  • Problem: For very large numbers, reversing the digits could cause an integer overflow. Java’s int data type has a maximum limit of 2,147,483,647, and reversing a number larger than this could lead to incorrect results.
  • Solution: Use a long data type to handle larger numbers:
long reversedNum = 0;

3. Single-Digit Numbers

  • Problem: Single-digit numbers like 7 or 9 are always palindromes, but the code processes them unnecessarily.
  • Solution: You can optimize for single-digit numbers by adding a simple condition:
if (num >= 0 && num < 10) {
    System.out.println(originalNum + " is a palindrome.");
    return;
}

4. Handling Zero

  • Problem: The number 0 is technically a palindrome and the code handles it correctly, but you might want to handle zero specifically depending on your use case.
  • Solution: No special handling is needed unless specific use cases require it.

Enhanced Code:

Here’s an enhanced version of the code that accounts for negative numbers and integer overflow:

public class PalindromeCheck {
    public static void main(String[] args) {
        int num = 121; // Example number to check
        if (num < 0) {
            System.out.println(num + " is not a palindrome.");
            return;
        }

        int originalNum = num;
        long reversedNum = 0; // Using long to avoid overflow

        while (num != 0) {
            int digit = num % 10;
            reversedNum = reversedNum * 10 + digit;
            if (reversedNum > Integer.MAX_VALUE) {
                System.out.println("Overflow occurred, unable to check palindrome.");
                return;
            }
            num /= 10;
        }

        if (originalNum == reversedNum) {
            System.out.println(originalNum + " is a palindrome.");
        } else {
            System.out.println(originalNum + " is not a palindrome.");
        }
    }
}

Challenge Question:

Which of the following numbers is a palindrome?

  1. 123
  2. 444
  3. 789
  4. 9889

Let me know your answer in the comments section, and don’t forget to visit our Testers Journey blog for more coding tutorials and tips. Keep learning, keep testing!

Conclusion

That’s it! Now you know how to check if a number is a palindrome using a simple while loop in Java. This method is straightforward, easy to implement, and perfect for beginners who are just getting started with programming.

Be sure to check out more articles on Testers Journey Blogs :-

Don’t forget to check out our video tutorial on this topic on our YouTube channel. If you have any questions or suggestions for future topics, drop a comment below!

For more tutorials and insights, follow along on our Blogs, YouTube channel and Facebook Page. Happy coding!

Add a Comment

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