Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program to check whether the given number is a palindrome?

A number is a palindrome if it reads the same forwards and backwards, like 121 or 1331. The standard way to check this in Java is to reverse the number using integer arithmetic and compare the reversed value with the original: keep a copy of the input, repeatedly strip the last digit with the modulo operator (% 10) while rebuilding the reversed number and dividing the input by 10, then test whether the reversed number equals the original. If they match, the number is a palindrome.

What Is a Palindrome Number?

A palindrome number stays identical when its digits are reversed. The mirror symmetry of the digits is the only thing that matters, the magnitude of the number is irrelevant.

  • Palindromes: 0, 7, 22, 121, 1331, 707, 94049. Reversing the digits gives back the same number.
  • Not palindromes: 123, 10, 1234, 120. Reversing the digits produces a different value.
  • Single digits: every number from 0 to 9 is trivially a palindrome, because one digit reads the same both ways.

The Reverse-and-Compare Approach

The most common and most efficient technique works purely with integer math. Follow these steps:

  • Save the input in a separate variable (for example originalNum) so it survives the loop, and initialize reversedNum to 0.
  • Extract the last digit of the working number with the modulo operator: digit = num % 10.
  • Append that digit to the reversed number: reversedNum = reversedNum * 10 + digit.
  • Drop the processed digit using integer division: num = num / 10.
  • Repeat while num is not zero, then compare: if originalNum == reversedNum, the number is a palindrome.

Complete Java Program to Check a Palindrome Number

The program below is self-contained and compiles as written. Save it as PalindromeNumber.java, compile with javac, and run it.

public class PalindromeNumber {
    public static void main(String[] args) {
        int num = 12321;
        int originalNum = num;
        int reversedNum = 0;

        while (num != 0) {
            int digit = num % 10;
            reversedNum = reversedNum * 10 + digit;
            num = num / 10;
        }

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

Output:

12321 is a palindrome number.

Change num to 12345 and the same program prints 12345 is not a palindrome number.

Reading the Number From User Input

To check any number the user types, read it with a Scanner. The core logic is unchanged.

import java.util.Scanner;

public class PalindromeCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        int originalNum = num;
        int reversedNum = 0;

        while (num != 0) {
            reversedNum = reversedNum * 10 + num % 10;
            num /= 10;
        }

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

Sample run:

Enter a number: 1221
1221 is a palindrome number.

Alternative Approaches

The reverse-and-compare method is preferred, but two string-based variants are worth knowing, especially when you are comparing solutions in an interview or a code review.

1. String + StringBuilder.reverse()

Convert the number to a string, reverse it with StringBuilder, and compare the two strings. It is the most readable option.

public class PalindromeString {
    public static void main(String[] args) {
        int num = 1331;
        String str = String.valueOf(num);
        String reversed = new StringBuilder(str).reverse().toString();

        if (str.equals(reversed)) {
            System.out.println(num + " is a palindrome number.");
        } else {
            System.out.println(num + " is not a palindrome number.");
        }
    }
}
1331 is a palindrome number.

2. Two-Pointer on the String

Walk one pointer in from the left and one in from the right, comparing characters as they meet. It avoids building a second reversed string.

public class PalindromeTwoPointer {
    public static void main(String[] args) {
        int num = 1221;
        String str = String.valueOf(num);
        int left = 0, right = str.length() - 1;
        boolean isPalindrome = true;

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                isPalindrome = false;
                break;
            }
            left++;
            right--;
        }

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

Comparing the Approaches

ApproachTimeSpaceBest For
Reverse the numberO(log10 n)O(1)Most efficient; no string allocation.
StringBuilder.reverse()O(d)O(d)Readability and quick prototypes.
Two-pointer on stringO(d)O(d)Early exit on the first mismatch.

Here n is the value of the number and d is its digit count, so d is roughly log10 n. For typical inputs the difference is negligible, but the integer approach wins when you must avoid object allocation.

Handling Negatives and Edge Cases

  • Negative numbers: values like -121 are not palindromes, because the leading minus sign cannot mirror at the end. The integer method returns false automatically, since reversedNum is always non-negative.
  • Zero and single digits: 0 through 9 are always palindromes and the loop handles them correctly.
  • Trailing zeros: numbers ending in 0 other than 0 itself, such as 120, are never palindromes because the reversed value loses the trailing zero (120 reversed is 21).
  • Overflow: for very large inputs near the int limit, reversing can overflow. Use long for the reversed value, or the string approach, to stay safe.

Why This Matters Beyond the Exercise

Palindrome checks are a staple of coding interviews and a clean way to practise loops, the modulo operator, and string handling. Java is also the most widely used language for Selenium automation, so the same fundamentals you sharpen here carry straight into writing test logic. When that logic ships, you can validate it across thousands of browser and OS combinations on the TestMu AI cloud, so the behaviour you verified locally holds in real environments and CI pipelines.

Frequently Asked Questions

What is a palindrome number?

A palindrome number reads the same forwards and backwards. For example, 121, 1331, and 707 are palindromes because reversing their digits produces the same value, while 123 is not.

How do you check if a number is a palindrome in Java?

Store the original number, reverse it with a while loop that extracts the last digit using % 10 and removes it using / 10 while building reversedNum = reversedNum * 10 + digit, then compare the reversed number with the original. If they are equal, the number is a palindrome.

Are negative numbers palindromes in Java?

No. Negative numbers such as -121 are not palindromes because the leading minus sign cannot be mirrored at the end. The reverse-and-compare method naturally returns false for negatives, since the reversed value is always non-negative.

Can you check a palindrome number without converting it to a string?

Yes. The reverse-the-number approach uses only integer arithmetic (% and /), so it never converts the number to a string. This is the most memory-efficient method, running in O(log10 n) time and O(1) space.

What is the time complexity of a palindrome number check in Java?

The reverse-the-number method runs in O(log10 n) time because it processes each digit once, and uses O(1) extra space. String-based methods run in O(d) time and O(d) space, where d is the number of digits.

Is 0 a palindrome number?

Yes. Zero and every single-digit number from 0 to 9 are trivially palindromes, because a single digit reads the same forwards and backwards.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests