## Java Programming Examples Tutorial Index

This Java tutorial helps you understand Armstrong numbers and how to write a Java program to validate them. Here you will learn to verify whether the integer entered by the user is an Armstrong number or not.

## What is an Armstrong Number?

An Armstrong number is a positive integer equal to the sum of all its digits raised to the power of the total count of digits.

Consider the number 1634:

``````(1^4) + (6^4) + (3^4) + (4^4)
= (1 * 1 * 1 * 1) + (6 * 6 * 6 * 6) + (3 * 3 * 3 * 3) + (4 * 4 * 4 * 4)
= 1 + 1296 + 81 + 256
= 1634``````

In this case, 1634 is a four-digit number, and when each of its digits is raised to the power of 4 (the total number of digits), the sum equals the original number.

## Java Program to Check Armstrong Number

``````import java.util.Scanner;

public class ArmstrongNumberChecker {
public static void main(String[] args) {
int number, originalNumber, lastDigit, sum = 0, digits = 0, temp;
Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");
number = scanner.nextInt();
originalNumber = number;

// Calculate the number of digits
temp = number;
while (temp != 0) {
temp /= 10;
digits++;
}

while (originalNumber != 0) {
// lastDigit contains the last digit of the number
lastDigit = originalNumber % 10;

// raise the last digit to the power of digits and add it to the sum
sum += Math.pow(lastDigit, digits);

// remove last digit from the original number
originalNumber /= 10;
}

// Check if the sum equals the original number
if (sum == number)
System.out.printf("%d is an Armstrong number.\n", number);
else
System.out.printf("%d is not an Armstrong number.\n", number);
}
}``````

Program Output:

Here are some examples of running the program and the corresponding output:

``````Enter an integer: 123
123 is not an Armstrong number.``````
``````Enter an integer: 9474
9474 is an Armstrong number.``````

Program Explanation:

1. The program asks the user to enter an integer with the help of Java's Scanner class.
2. The program calculates the digit count of the input number.
3. The program enters a loop where it raises each digit to the power of the total number of digits and adds this to a sum.
4. After processing all the digits, the sum is compared to the original number.
5. Finally, the program will print that the input number is an Armstrong number if the sum and original number are equal. If not, it will print that the input number is not an Armstrong number.