Core Java

Checking if a Number is a Palindrome in Java

In coding challenges, checking if a number is a palindrome is a basic and common problem. A palindrome refers to a sequence that reads the same in both directions and while it is often associated with words or strings (e.g., madam or racecar), numbers can also exhibit this property. A palindromic number is one that remains identical when its digits are reversed. This article explores different approaches to check if a number is a palindrome in Java.

1. Problem Overview

Given a number, determine whether it is a palindrome. To better illustrate the concept of a palindromic number, the following examples are examined:

  • Example 1: Input: 121
    • If we reverse the digits of 121, we still get 121. Therefore, the number is a palindrome.
  • Example 2: Input: 12321
    • Reversing the digits results in the same number, 12321. Thus, it is a palindrome.
  • Example 3: Input: 123
    • Reversing the digits of 123 gives us 321, which is different from the original number. Therefore, it is not a palindrome.
  • Example 4: Input: -121
    • Even though the digits may appear symmetric, the negative sign makes the number unequal when reversed. Thus, negative numbers are not considered palindromes.

The problem can be tackled using various approaches, as demonstrated in the following sections of this article.

2. Convert the Number to a String

A simple way to check if a number is a palindrome is to convert it into a string. Once the number is represented as a string, we can reverse the string and compare it with the original string. If they are the same, the number is a palindrome.

public class PalindromeCheckerString {

    public static boolean isPalindrome(int number) {
        
        String numStr = String.valueOf(number);
        String reversedStr = new StringBuilder(numStr).reverse().toString();
        return numStr.equals(reversedStr);
    }

    public static void main(String[] args) {
        int number1 = 121;
        int number2 = 123;
        int number3 = -121;

        System.out.println(number1 + " is a palindrome: " + isPalindrome(number1));
        System.out.println(number2 + " is a palindrome: " + isPalindrome(number2));
        System.out.println(number3 + " is a palindrome: " + isPalindrome(number3));
    }
}

In this code snippet, The isPalindrome method takes an integer as input. It starts by converting the integer to a string using String.valueOf(). Next, it creates a StringBuilder object to reverse the string representation of the number. The method then checks if the original string (numStr) is equal to the reversed string (reversedStr) using the .equals() method. If they are equal, the method returns true, indicating that the number is a palindrome; otherwise, it returns false.

When the program is executed, the expected output will be:

121 is a palindrome: true
123 is a palindrome: false
-121 is a palindrome: false

3. Reverse the Number Mathematically

This approach involves reversing the digits of the number mathematically without converting it into a string. We can achieve this by repeatedly extracting the last digit and appending it to a reversed number.

public class PalindromeCheckerMath {

    public static boolean isPalindrome(int number) {
        // Handle negative numbers and multiples of 10
        if (number < 0 || (number % 10 == 0 && number != 0)) {
            return false;
        }

        int reversedHalf = 0;
        while (number > reversedHalf) {
            reversedHalf = reversedHalf * 10 + number % 10;
            number /= 10;
        }

        // Check if the original number is equal to the reversed half
        return number == reversedHalf || number == reversedHalf / 10;
    }

    public static void main(String[] args) {
        int number1 = 121;
        int number2 = -121;
        int number3 = 12321;

        System.out.println(number1 + " is a palindrome: " + isPalindrome(number1));
        System.out.println(number2 + " is a palindrome: " + isPalindrome(number2));
        System.out.println(number3 + " is a palindrome: " + isPalindrome(number3));
    }
}

In this code example, the isPalindrome method starts by checking if the number is negative or a multiple of 10 (except for 0), as these cannot be palindromes. Then, it reverses half of the number using a while loop: it constructs reversedHalf by taking the last digit of the original number and appending it to reversedHalf until the original number is less than or equal to reversedHalf.

Finally, it checks if the original number is equal to reversedHalf or if it equals reversedHalf divided by 10 (which handles numbers with an odd number of digits). The expected output would be as follows:

output generated by executing the Java palindrome integer test example

4. Digit-by-Digit Comparison Method

This approach allows us to compare digits from both ends of the number without reversing the entire number. It works by extracting the leftmost and rightmost digits and comparing them. If any of the digits don’t match, the number is not a palindrome.

public class PalindromeCheckerDigitCheck {

    public static boolean isPalindrome(int number) {
        // Negative numbers are not palindromes
        if (number < 0) {
            return false;
        }

        // Count the number of digits
        int divisor = 1;
        while (number / divisor >= 10) {
            divisor *= 10;
        }

        // Compare the digits from the front and back
        while (number > 0) {
            int leftDigit = number / divisor;
            int rightDigit = number % 10;

            // If the digits are different, it's not a palindrome
            if (leftDigit != rightDigit) {
                return false;
            }

            // Remove the leftmost and rightmost digits
            number = (number % divisor) / 10;
            divisor /= 100; // Reduce the divisor by two digits
        }

        return true;
    }

    public static void main(String[] args) {
        int number1 = 121;
        int number2 = 123;
        int number3 = 12321;

        System.out.println(number1 + " is a palindrome: " + isPalindrome(number1));
        System.out.println(number2 + " is a palindrome: " + isPalindrome(number2));
        System.out.println(number3 + " is a palindrome: " + isPalindrome(number3));
    }
}


In this example, the isPalindrome method in the PalindromeCheckerDigitCheck class begins by checking if the number is negative, returning false since negative numbers cannot be palindromes. A divisor is initialized at 1 and multiplied by 10 in a loop until it is large enough to extract the leftmost digit, as in the case of 121, where the divisor becomes 100.

During each loop iteration, the leftmost and rightmost digits are compared. The left digit is calculated by dividing the number by the divisor, while the right digit is determined using the modulus operator (number % 10). If the digits don’t match, the method returns false. If they match, the digits are removed, and the divisor is reduced by 100.

This process continues until all digits are compared. If no mismatches are found, the method returns true, confirming that the number is a palindrome. The expected output is:

121 is a palindrome: true
123 is a palindrome: false
12321 is a palindrome: true

5. Conclusion

In this article, different methods for testing if an integer is a palindrome in Java were explored. We examined approaches such as converting the number to a string, reversing it, and comparing the original and reversed values. Generally learning how to check if an integer is a palindrome improves problem-solving skills and helps understand how algorithms work in Java.

6. Download the Source Code

This article explored how to test if an integer is a palindrome in Java.

Download
You can download the full source code of this example here: java palindrome integer test

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button