Java Program to Check Palindrome Number (Without Using String)

A palindrome number is a number that reads the same from left to right and right to left. For example, 121, 1331, and 12321 are palindrome numbers because reversing their digits does not change their values.

Checking whether an integer is a palindrome is a common Java programming interview question. It helps developers practice loops, arithmetic operators, conditional statements, and problem-solving techniques.

In Java, you can check a palindrome number without converting the integer into a string. The basic idea is to extract digits using the modulus operator (%) and remove digits using integer division (/).

In this tutorial, I will explain how to check whether an integer is a palindrome in Java. I will start with a simple program that reverses the number. Then I will show an improved approach that reverses only half of the digits to avoid integer overflow.

What Is a Palindrome Number?

A palindrome number remains unchanged when its digits are read in reverse order.

Here are some examples:

Number Reversed Number Palindrome?
121 121 Yes
1331 1331 Yes
123 321 No
7 7 Yes
120 021 No
0 0 Yes

Note: Negative integers are considered non-palindromes in this tutorial because the minus sign appears only at the beginning of the original number.

Method 1: Check Palindrome Number in Java Using a While Loop

The first approach reverses all digits of the integer and compares the reversed value with the original number.

For example, consider the number 121. Reversing its digits produces 121. Since the original number and reversed number are equal, the number is a palindrome.

Java Program

Create a Java class named PalindromeNumberExample and add the following code:

public class PalindromeNumberExample {

    public static void main(String[] args) {

        int number = 12321;

        if (isPalindrome(number)) {
            System.out.println(number + " is a palindrome number.");
        } else {
            System.out.println(number + " is not a palindrome number.");
        }
    }

    /**
     * Checks whether an integer is a palindrome.
     *
     * @param number the integer to check
     * @return true if the number is a palindrome; otherwise false
     */
    public static boolean isPalindrome(int number) {

        // Negative numbers are not palindromes.
        if (number < 0) {
            return false;
        }

        int originalNumber = number;
        long reversedNumber = 0;

        while (number != 0) {

            // Extract the last digit.
            int digit = number % 10;

            // Append the digit to the reversed number.
            reversedNumber = reversedNumber * 10 + digit;

            // Remove the last digit.
            number = number / 10;
        }

        // Compare the reversed number with the original.
        return originalNumber == reversedNumber;
    }
}

Output

12321 is a palindrome number.

How Does the Program Work?

The program uses three arithmetic operations:

  • number % 10 extracts the last digit of the number.
  • reversedNumber * 10 + digit adds the extracted digit to the reversed number.
  • number / 10 removes the last digit from the number.

The while loop repeats these operations until all digits have been processed.

The program stores the reversed value in a long variable. This prevents overflow when reversing a valid 32-bit integer whose reversed digits do not fit into an int.

Dry Run: Checking Whether 121 Is a Palindrome

Let's trace the algorithm with the input 121.

Iteration Current Number Last Digit Reversed Number
1 121 1 1
2 12 2 12
3 1 1 121

After the loop finishes:

  • Original number = 121
  • Reversed number = 121

Since both values are equal, the method returns true.

Method 2: Check Palindrome Number Without Reversing the Entire Integer

The first solution is easy to understand. However, an interview may require you to avoid reversing the entire integer.

A useful improvement is to reverse only half of the digits.

For a palindrome, the first half of the number must match the second half in reverse order. For example, in 1221, the first half is 12, and reversing the second half also produces 12.

This approach avoids overflow because it never needs to construct the complete reversed integer.

Java Program

public class PalindromeHalfReverseExample {

    public static void main(String[] args) {

        int[] numbers = {121, 1221, 12321, 123, 10, 0, -121};

        for (int number : numbers) {
            System.out.println(number + " : " + isPalindrome(number));
        }
    }

    /**
     * Checks whether an integer is a palindrome by reversing
     * only the second half of its digits.
     *
     * @param number the integer to check
     * @return true if the number is a palindrome; otherwise false
     */
    public static boolean isPalindrome(int number) {

        // Negative numbers and nonzero numbers ending in 0
        // cannot be palindromes.
        if (number < 0 || (number != 0 && number % 10 == 0)) {
            return false;
        }

        int reversedHalf = 0;

        // Stop when the reversed half has as many digits
        // as the remaining part of the number.
        while (number > reversedHalf) {

            int digit = number % 10;

            reversedHalf = reversedHalf * 10 + digit;

            number = number / 10;
        }

        // Even digits: both halves are equal.
        // Odd digits: ignore the middle digit.
        return number == reversedHalf
                || number == reversedHalf / 10;
    }
}

Output

121 : true
1221 : true
12321 : true
123 : false
10 : false
0 : true
-121 : false

Explanation

This solution divides the original number into two parts.

  1. Reject negative numbers because their minus sign cannot appear at both ends.
  2. Reject nonzero numbers ending in 0. Such numbers cannot be palindromes because they would need a leading zero.
  3. Extract digits from the right side and append them to reversedHalf.
  4. Stop when the reversed half becomes greater than or equal to the remaining number.
  5. Compare both halves to determine whether the number is a palindrome.

For a number with an even number of digits, both halves must be equal.

For a number with an odd number of digits, the middle digit does not affect whether the number is a palindrome. The expression reversedHalf / 10 removes that middle digit before comparison.

Example 1: Even Number of Digits

Consider the number 1221.

  • Start with number = 1221 and reversedHalf = 0.
  • After the first iteration: number = 122 and reversedHalf = 1.
  • After the second iteration: number = 12 and reversedHalf = 12.
  • Both halves are equal, so the result is true.

Example 2: Odd Number of Digits

Consider the number 12321.

  • Start with number = 12321 and reversedHalf = 0.
  • After the first iteration: number = 1232 and reversedHalf = 1.
  • After the second iteration: number = 123 and reversedHalf = 12.
  • After the third iteration: number = 12 and reversedHalf = 123.
  • Remove the middle digit: 123 / 10 = 12.
  • The remaining halves match, so the result is true.

Method 3: Check Palindrome Number Using StringBuilder

Another approach converts the number into a string and reverses it using StringBuilder. This solution is shorter, but it does not satisfy interview questions that prohibit string conversion.

Java Program

public class PalindromeStringExample {

    public static void main(String[] args) {

        int number = 1331;

        System.out.println(
                number + " is a palindrome: " + isPalindrome(number)
        );
    }

    /**
     * Checks whether a non-negative integer reads the same
     * forward and backward.
     *
     * @param number the integer to check
     * @return true if the number is a palindrome; otherwise false
     */
    public static boolean isPalindrome(int number) {

        if (number < 0) {
            return false;
        }

        String original = Integer.toString(number);

        String reversed = new StringBuilder(original)
                .reverse()
                .toString();

        return original.equals(reversed);
    }
}

Output

1331 is a palindrome: true

The Integer.toString() method converts the integer into a string. The reverse() method reverses its characters. Finally, equals() compares the original and reversed strings.

This method is readable, but it creates additional objects. For coding interviews that focus on arithmetic operations, prefer the second method.

How to Run the Java Programs

You can run these examples using a Java IDE such as IntelliJ IDEA, Eclipse, or Visual Studio Code. You can also compile and execute them from a terminal.

  1. Install a JDK if Java is not already available on your computer.
  2. Create a file named PalindromeNumberExample.java.
  3. Copy the code from Method 1 into the file.
  4. Open a terminal in the folder containing the file.
  5. Compile and run the program using the following commands.
javac PalindromeNumberExample.java
java PalindromeNumberExample

For the other examples, save each class in a file matching its public class name and use that file name in the javac command.

Important Edge Cases

A reliable palindrome program should handle more than a few common examples.

Input Expected Result Reason
0 true Zero reads the same in both directions.
9 true Every non-negative single-digit number is a palindrome.
11 true Both digits are equal.
12321 true The digits are symmetric.
12345 false Reversed digits differ from the original.
1001 true Zeros in the middle do not affect symmetry.
100 false Reversing the digits does not preserve the number.
-121 false Negative numbers are excluded by definition.
2147483647 false The number is not symmetric; the arithmetic solutions handle it safely.

Time and Space Complexity

Let d represent the number of decimal digits in the input integer.

Approach Time Complexity Extra Space
Reverse entire number O(d) O(1)
Reverse half the number O(d) O(1)
StringBuilder reversal O(d) O(d)

The half-reversal approach performs approximately half as many digit-processing iterations as the full-reversal approach. Both arithmetic methods use constant extra space.

Common Mistakes When Checking Palindrome Numbers

1. Modifying the Original Number Without Saving It

In the full-reversal approach, the original number must be saved before the loop. Otherwise, the number becomes zero after all digits are removed, leaving no original value for comparison.

2. Ignoring Negative Numbers

A negative number such as -121 is not considered a palindrome because its sign does not appear at the end of the reversed representation.

3. Ignoring Integer Overflow

Reversing a large integer into an int may overflow. Use a long variable for full reversal or use the half-reversal technique to avoid constructing the complete reversed value.

4. Mishandling Numbers Ending in Zero

Numbers such as 10 and 120 are not palindromes. The half-reversal algorithm checks this condition before processing the digits.

Frequently Asked Questions

Can I check a palindrome number in Java without converting it to a string?

Yes. Use the modulus operator (%) to extract digits and integer division (/) to remove digits. Both arithmetic solutions in this tutorial work without string conversion.

Is 0 a palindrome number?

Yes. Zero reads the same forward and backward.

Are negative numbers palindromes?

No. Under the usual programming-interview definition, negative integers are not palindromes because of the minus sign.

Which palindrome algorithm is best for Java interviews?

The half-reversal algorithm is a strong choice. It uses constant extra space, avoids reversing the entire integer, and handles the full range of int values without overflow.

Can the program check very large numbers?

The examples use the Java int type. For values beyond the int range, you can adapt the arithmetic approach to long values. For integers larger than the long range, use BigInteger or a string-based representation and choose an algorithm suitable for that representation.

Conclusion

In this tutorial, you learned how to check whether an integer is a palindrome in Java using three approaches.

The first approach reverses the complete number using a while loop. It is easy to understand and demonstrates how modulus and integer division work together. The second approach reverses only half of the digits. It is more efficient in practice and avoids overflow. The third approach uses StringBuilder for cases where string conversion is allowed.

For Java coding interviews, I recommend practicing the half-reversal approach. It demonstrates a clear understanding of number manipulation and handles important edge cases without additional data structures.

Official Java Documentation

You can refer to the following official Oracle Java documentation to learn more about the APIs used in this tutorial:

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments