Palindrome Number Program in Java Using while & for Loop

โšก Smart Summary

Palindrome Number Program in Java determines whether a value reads identically forwards and backwards by reversing its digits. This article presents the algorithm, a while loop version, a for loop version, a string based method, recursion, edge cases, and complexity analysis with verified output.

  • ๐Ÿ” Core Definition: A palindrome number remains unchanged after its digits are reversed, as with 131, 393, and 34043.
  • โž— Reversal Technique: The modulus operator extracts the last digit and integer division removes it, one digit per pass.
  • ๐Ÿงฎ Accumulator Rule: Each pass multiplies the running sum by ten before adding the freshly extracted digit.
  • ๐Ÿ”‚ Loop Choice: A while loop and a for loop produce identical results, provided the division appears exactly once per iteration.
  • ๐Ÿ”ค String Method: StringBuilder reverse compares text directly and works for words as well as numbers.
  • โš ๏ธ Edge Cases: Single digit values are always palindromes, negative values never are, and trailing zeros break the numeric comparison.
  • โฑ๏ธ Complexity Profile: Both loop versions run in O(log n) time proportional to the digit count and use O(1) extra space.

Palindrome Number Program in Java

What is Palindrome Number?

A Palindrome number is a number that remains the same number when it is reversed. For example, 131. When its digits are reversed, it remains the same number. A palindrome number has reflection symmetry at the vertical axis. The same idea applies to a word that has the same spelling when its letters are reversed.

Examples of Palindrome Number in Java

121, 393, 34043, 111, 555, 48084

Examples of Palindrome Words

LOL, MADAM

Every single digit value from 0 to 9 is a palindrome by definition, because reversing one digit produces the same digit.

Palindrome Number Algorithm

Below is the palindrome number algorithm logic in Java:

  • Fetch the input number that needs to be checked for being a Palindrome.
  • Copy the number into a temporary variable and reverse it.
  • Compare the reversed and original number.
  • If they are the same, the number is a “palindrome number”.
  • Otherwise the number is not a “palindrome number”.

The reversal itself is the only part that needs care. Two arithmetic operations do all the work, and the table below traces them for the value 171.

Pass a (remaining number) lastDigit = a % 10 sum = (sum * 10) + lastDigit a = a / 10
1 171 1 1 17
2 17 7 17 1
3 1 1 171 0

After the final pass, sum holds 171, which equals the original input, so the number is confirmed as a palindrome.

How to check whether input number is Palindrome or not

Below is a palindrome program in Java with a WHILE loop. The loop continues while digits remain, and the print statements expose the state of every variable during each pass.

package com.guru99;

public class PalindromeNum {

    public static void main(String[] args)
    {

        int lastDigit, sum = 0, a;
        int inputNumber = 171; //It is the number to be checked for palindrome

        a = inputNumber;

        // Code to reverse a number
        while(a > 0)
        {   System.out.println("Input Number " + a);
            lastDigit = a % 10; //getting remainder
            System.out.println("Last Digit " + lastDigit);
            System.out.println("Digit " + lastDigit + " was added to sum " + (sum * 10));
            sum = (sum * 10) + lastDigit;
            a = a / 10;

        }

        // if the given number equals sum then the number is a palindrome, otherwise not
        if(sum == inputNumber)
            System.out.println("Number is palindrome ");
        else
            System.out.println("Number is not palindrome");

    }

}

Code Output:

Input Number 171
Last Digit 1
Digit 1 was added to sum 0
Input Number 17
Last Digit 7
Digit 7 was added to sum 10
Input Number 1
Last Digit 1
Digit 1 was added to sum 170
Number is palindrome

Program to Check Palindrome using for loop

Below is a Java program for palindrome using a for loop. The header carries the exit test and the division, so the loop body must not divide again.

package com.guru99;

public class PalindromeNumForLoop {

    public static void main(String[] args)
    {

        int lastDigit, sum = 0, a;
        int inputNumber = 185; //It is the number to be checked for palindrome

        a = inputNumber;

        // Code to reverse a number
        for( ; a != 0; a /= 10 )
        {   System.out.println("Input Number " + a);
            lastDigit = a % 10; //getting remainder
            System.out.println("Last Digit " + lastDigit);
            System.out.println("Digit " + lastDigit + " was added to sum " + (sum * 10));
            sum = (sum * 10) + lastDigit;

        }

        // if the given number equals sum then the number is a palindrome, otherwise not
        if(sum == inputNumber)
            System.out.println("Number is palindrome ");
        else
            System.out.println("Number is not palindrome");

    }

}

Code Output:

Input Number 185
Last Digit 5
Digit 5 was added to sum 0
Input Number 18
Last Digit 8
Digit 8 was added to sum 50
Input Number 1
Last Digit 1
Digit 1 was added to sum 580
Number is not palindrome

โš ๏ธ Warning: A frequent mistake is to keep a = a / 10; inside the for loop body while the header already contains a /= 10. The number is then divided twice per pass, half the digits are skipped, and a genuine palindrome such as 121 is reported incorrectly as not a palindrome.

Palindrome Program in Java Using String Reverse

Converting the value to text allows StringBuilder to reverse it in one call. The same method also works for words, which the numeric approach cannot handle.

package com.guru99;

public class PalindromeString {

    public static boolean isPalindrome(String text) {
        // ignore case so MADAM and madam behave identically
        String clean = text.toLowerCase();
        String reversed = new StringBuilder(clean).reverse().toString();
        return clean.equals(reversed);
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("121"));
        System.out.println(isPalindrome("MADAM"));
        System.out.println(isPalindrome("Java"));
    }
}

Code Output:

true
true
false

Palindrome Program in Java Using Recursion

Recursion compares the outermost pair of characters and then calls itself on the shrinking middle section. The method stops when fewer than two characters remain.

package com.guru99;

public class PalindromeRecursion {

    public static boolean isPalindrome(String text, int left, int right) {
        // base case: pointers met or crossed
        if (left >= right) {
            return true;
        }
        if (text.charAt(left) != text.charAt(right)) {
            return false;
        }
        return isPalindrome(text, left + 1, right - 1);
    }

    public static void main(String[] args) {
        String value = "34043";
        System.out.println(value + " is palindrome: "
                + isPalindrome(value, 0, value.length() - 1));

        String other = "12345";
        System.out.println(other + " is palindrome: "
                + isPalindrome(other, 0, other.length() - 1));
    }
}

Code Output:

34043 is palindrome: true
12345 is palindrome: false

Edge Cases and Method Comparison

Three inputs break naive implementations, so every version should be tested against them before use.

  1. Negative numbers: Values such as -121 are never palindromes, because the minus sign has no counterpart at the end. Guard with if (inputNumber < 0) return false;.
  2. Trailing zeros: The value 100 reverses to 1, so the comparison correctly returns false. Only the number 0 itself passes among values ending in zero.
  3. Integer overflow: Reversing a large int such as 1,999,999,999 can exceed the int range. Declare sum as a long when the input may approach the limit.

The table below compares the four approaches shown on this page.

Method Time Complexity Space Complexity Works for Words Notes
While loop O(log n) O(1) No Clearest demonstration of digit reversal
For loop O(log n) O(1) No Identical logic, division in the header only
StringBuilder reverse O(n) O(n) Yes Shortest code, allocates a new string
Recursion O(n) O(n) stack Yes Useful for interview discussions on recursion

The digit extraction pattern used here reappears in many exercises. Continue with the Fibonacci series in Java, the Java program to check a prime number, and the Bubble Sort algorithm in Java. For the loop syntax itself, review the for each loop in Java and the wider Java tutorial, and see Java strings for the text based method.

FAQs

No. The minus sign appears only at the front, so -121 reversed is 121- which never matches. Add an early guard that returns false for any value below zero.

Multiplying shifts the digits already collected one place to the left, which frees the units position for the newly extracted digit. This rebuilds the number in reverse order.

The reversed value can exceed the int maximum of 2147483647 and wrap to a negative result. Declare the accumulator as a long, or compare the values as strings instead.

Read the value with Scanner and nextInt, then pass it to the same reversal logic. Wrap the read in a try block so that non-numeric input does not crash the program.

Usually yes when asked to review the code explicitly. They rarely flag it unprompted, so always test a known palindrome such as 121 rather than trusting a passing example.

The question tests loop control, integer arithmetic, and edge case reasoning in a few lines. It also reveals whether a candidate verifies AI generated code before submitting it.

Summarize this post with: