Armstrong Number in Java | Spring Java Lab

Armstrong Number in Java

An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.

Examples:

  • 153 β†’ 1Β³ + 5Β³ + 3Β³ = 153
  • 9474 β†’ 9⁴ + 4⁴ + 7⁴ + 4⁴ = 9474

Java Program to Check Armstrong Number

import java.util.Scanner;

public class ArmstrongCheck {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        int original = number;
        int result = 0;
        int digits = String.valueOf(number).length();

        while (number != 0) {
            int digit = number % 10;
            result += Math.pow(digit, digits);
            number /= 10;
        }

        if (result == original) {
            System.out.println(original + " is an Armstrong number.");
        } else {
            System.out.println(original + " is not an Armstrong number.");
        }
    }
}

Output

Enter a number: 153  
153 is an Armstrong number.

Explanation

  • The number of digits is calculated using String.valueOf(number).length().
  • Each digit is raised to the power of the total digits and added.
  • If the sum matches the original number, it’s an Armstrong number.

Conclusion

This is a commonly asked Java interview question to test your knowledge of loops, conditionals, and number operations.