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

Java Program to Check an Armstrong Number

An Armstrong number is a number that equals the sum of each of its digits raised to the power of the total number of digits. For example, 153 has three digits, and 13 + 53 + 33 = 1 + 125 + 27 = 153. In Java, you check it by extracting each digit with the modulo (%) and division (/) operators, raising every digit to the digit-count power, summing the results, and comparing that sum to the original number.

Below you will find the definition with worked examples, a complete runnable Java program, a version without Math.pow, a range finder, a step-by-step dry run, and the common bugs to avoid. Armstrong numbers are also called narcissistic numbers, and the digit-extraction pattern you learn here applies to many other automation testing coding exercises.

What Is an Armstrong Number

An Armstrong number (also known as a narcissistic number or a pluperfect digital invariant) is a number that is equal to the sum of its own digits, where each digit is raised to the power of the total count of digits in the number. The key detail people miss is that the exponent is not always 3 — it is the number of digits. For a 3-digit number the power is 3; for a 4-digit number the power is 4.

Here are the classic examples:

  • 153 (3 digits): 13 + 53 + 33 = 1 + 125 + 27 = 153
  • 370 (3 digits): 33 + 73 + 03 = 27 + 343 + 0 = 370
  • 9474 (4 digits): 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Every single-digit number from 0 to 9 is trivially an Armstrong number, because a digit raised to the power of 1 is itself. The well-known three-digit Armstrong numbers are 153, 370, 371, and 407, while four-digit examples include 1634, 8208, and 9474.

The Logic Explained

Checking an Armstrong number in Java comes down to five clear steps. Master these and you can write the program from memory:

  • Save the original. Copy the input into a second variable, because the next step destroys the working copy.
  • Count the digits. The number of digits is the exponent you will raise each digit to.
  • Extract each digit. Use num % 10 to grab the last digit, then num /= 10 to drop it. Repeat until the number becomes 0.
  • Raise and sum. Raise every extracted digit to the digit-count power and add it to a running total.
  • Compare. If the total equals the saved original, the number is an Armstrong number; otherwise it is not.

The two arithmetic operators doing all the work are modulo (%) and integer division (/). Modulo by 10 returns the rightmost digit, and integer division by 10 removes it. Looping these two operations peels a number apart one digit at a time, which is the foundation of dozens of Java number programs.

Java Program to Check an Armstrong Number

This complete, runnable program reads a number from the user, counts its digits dynamically so it works for any length, and then applies the Armstrong check. Counting the digits at runtime is what makes this version correct for 3-digit, 4-digit, and larger numbers alike.

import java.util.Scanner;

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

        int original = num;   // 1. Save the original before we modify num
        int sum = 0;

        // 2. Count the digits (this is the power we raise each digit to)
        int digits = String.valueOf(num).length();

        // 3. Extract each digit, raise it to "digits", and add to sum
        while (num != 0) {
            int lastDigit = num % 10;
            sum += Math.pow(lastDigit, digits);
            num /= 10;
        }

        // 4. Compare the sum against the saved original
        if (sum == original) {
            System.out.println(original + " is an Armstrong number.");
        } else {
            System.out.println(original + " is not an Armstrong number.");
        }
        sc.close();
    }
}

Run it with input 153 and it prints "153 is an Armstrong number." Try 9474 and it still works, because digits is computed from the input rather than hard-coded. Note that Math.pow returns a double, so it is implicitly narrowed when added to the int sum — fine for these magnitudes, but the next section shows a purely integer alternative.

Armstrong Number Without Math.pow

Math.pow works on double values, and for large inputs floating-point rounding can subtly distort the result. A manual integer power keeps every calculation in long, which is faster and avoids rounding surprises entirely. Here we extract the power calculation into its own helper method:

public class ArmstrongNoPow {

    // Integer power: base raised to exp, no floating point
    static long power(int base, int exp) {
        long result = 1;
        for (int i = 0; i < exp; i++) {
            result *= base;
        }
        return result;
    }

    static boolean isArmstrong(int number) {
        int original = number;
        int digits = String.valueOf(number).length();
        long sum = 0;

        while (number != 0) {
            int lastDigit = number % 10;
            sum += power(lastDigit, digits);
            number /= 10;
        }
        return sum == original;
    }

    public static void main(String[] args) {
        int[] tests = {153, 370, 9474, 9475};
        for (int n : tests) {
            System.out.println(n + " -> " + (isArmstrong(n) ? "Armstrong" : "Not Armstrong"));
        }
    }
}

Using a long for sum guards against overflow when a large number has several big digits raised to a high power. Wrapping the check in a reusable isArmstrong boolean method is also cleaner — you can call it from a loop, a unit test, or the range finder below without duplicating logic.

Find Armstrong Numbers in a Range

A common follow-up interview question is to print every Armstrong number between two bounds. Because we already isolated the logic into isArmstrong, the range finder is just a loop that calls it:

public class ArmstrongInRange {

    static boolean isArmstrong(int number) {
        int original = number;
        int digits = String.valueOf(number).length();
        long sum = 0;
        while (number != 0) {
            int d = number % 10;
            long p = 1;
            for (int i = 0; i < digits; i++) p *= d;
            sum += p;
            number /= 10;
        }
        return sum == original;
    }

    public static void main(String[] args) {
        int low = 1, high = 10000;
        System.out.println("Armstrong numbers between " + low + " and " + high + ":");
        for (int i = low; i <= high; i++) {
            if (isArmstrong(i)) {
                System.out.print(i + " ");
            }
        }
    }
}

Running this from 1 to 10000 prints the full set: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, and 9474. The single-digit numbers appear because each equals itself raised to the power of 1. The same loop-and-test pattern powers the Java program for printing prime numbers and most other range-based number exercises.

Armstrong Number Using Recursion

Interviewers often ask for a recursive version to test your grasp of base cases and self-calls. The recursion replaces the while loop: each call peels off one digit with % 10, adds that digit raised to the digit-count power, and recurses on number / 10. The base case is when the number reaches 0.

public class ArmstrongRecursion {

    static int digits;

    // Recursively sums each digit raised to the digit count
    static long sumPowers(int number) {
        if (number == 0) return 0;            // base case
        int lastDigit = number % 10;
        long power = 1;
        for (int i = 0; i < digits; i++) power *= lastDigit;
        return power + sumPowers(number / 10); // recursive call
    }

    static boolean isArmstrong(int number) {
        digits = String.valueOf(number).length();
        return sumPowers(number) == number;
    }

    public static void main(String[] args) {
        System.out.println(isArmstrong(153)); // true
        System.out.println(isArmstrong(154)); // false
    }
}

In terms of efficiency, every approach here runs in O(log₁₀n) time, because the number of iterations (or recursive calls) equals the digit count, which grows logarithmically with the value. The iterative versions use O(1) extra space, while the recursive version uses O(log₁₀n) stack space for the call frames. For typical inputs the difference is negligible, but the iterative loop is the safer default for very large numbers.

Step-by-Step Dry Run (153)

Tracing the loop by hand is the fastest way to truly understand the algorithm. For input 153, the digit count is 3, so each digit is raised to the power of 3. The list below shows every iteration of the while loop:

  • Iteration 1: num = 153, lastDigit (num % 10) = 3, lastDigit^3 = 27, sum = 27, num /= 10 = 15
  • Iteration 2: num = 15, lastDigit (num % 10) = 5, lastDigit^3 = 125, sum = 152, num /= 10 = 1
  • Iteration 3: num = 1, lastDigit (num % 10) = 1, lastDigit^3 = 1, sum = 153, num /= 10 = 0

After iteration 3, num becomes 0 and the loop exits. The final sum is 153, which equals the saved original 153, so the program correctly reports it as an Armstrong number. Following the same table for a non-Armstrong number like 154 would leave the sum at 154 vs. an original of 154... actually 1 + 125 + 64 = 190, which is not 154, so it would be rejected.

Common Mistakes and Troubleshooting

  • Modifying the original before saving it. The digit loop divides num down to 0. If you compare sum to num instead of a saved copy, you always compare against 0. Always store original = num first.
  • Hard-coding the power as 3. The exponent is the digit count, not always 3. A program that hard-codes 3 wrongly rejects 9474. Compute digits at runtime.
  • Integer overflow. Large numbers with high digit counts can exceed the int range. Use long for the running sum, or switch to BigInteger for very large inputs.
  • Trusting Math.pow blindly. Math.pow returns a double, so rounding can occasionally produce 124.999... instead of 125. A manual integer power or a Math.round avoids the off-by-one.
  • Mishandling 0 and negatives. The while (num != 0) loop never runs for an input of 0, and negative inputs break the digit count. Validate or guard the input before the loop.

Conclusion

Checking an Armstrong number in Java is a clean exercise in digit manipulation: save the original, count the digits, extract each digit with % and /, raise it to the digit-count power, sum, and compare. Use a runtime digit count so the program handles any length, prefer an integer power over Math.pow to dodge rounding, and use long to stay safe from overflow. Master this pattern and palindrome, reverse-number, and perfect-number programs all become straightforward variations of the same loop.

Frequently Asked Questions

What is an Armstrong number?

An Armstrong number is a number that equals the sum of each of its own digits raised to the power of the total count of digits. For example, 153 has three digits, and 13 + 53 + 33 equals 153, so it qualifies as a three-digit Armstrong number.

Is 153 an Armstrong number?

Yes. 153 has three digits, so each digit is raised to the power of three: 13 + 53 + 33 = 1 + 125 + 27 = 153. Because the sum equals the original number, 153 is a valid three-digit Armstrong number.

How do you check an Armstrong number in Java without Math.pow?

Replace Math.pow with an integer loop that multiplies the digit by itself the required number of times. This keeps the calculation in int or long, avoids floating-point rounding, and makes the result faster and more predictable for whole numbers.

How do you find all Armstrong numbers in a range in Java?

Loop from the lower bound to the upper bound, count the digits of each number, sum each digit raised to that digit count, and print the number when the sum equals the original. Moving the check into a reusable boolean method keeps the loop clean.

Why does my Armstrong program always print not an Armstrong number?

The usual cause is overwriting the original number inside the digit-extraction loop. Save the input in a separate variable before the loop, because the loop divides the working copy down to zero, leaving nothing valid to compare the digit-power sum against.

Can you check an Armstrong number in Java using recursion?

Yes. A recursive method peels off one digit per call with % 10, adds that digit raised to the digit-count power, and recurses on number / 10. The base case returns 0 when the number reaches zero. It produces the same result as the loop but uses stack space for each call.

What is the time complexity of an Armstrong number program in Java?

It is O(log₁₀n), because the loop or recursion runs once per digit and the digit count grows logarithmically with the number's value. The iterative versions use O(1) extra space, while the recursive version uses O(log₁₀n) stack space for its call frames.

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