Java Program to Check Armstrong Number

In this tutorial, we will learn how to write a Java program to check Armstrong's number.

Armstrong Number in Java

Armstrong Number in Java: A positive number is called Armstrong number if it is equal to the sum of cubes of its digits for example 0, 1, 153, 370, 371, 407, etc.
Let's try to understand why 153 is an Armstrong number.
153 = (1*1*1)+(5*5*5)+(3*3*3)  
where:  
(1*1*1)=1  
(5*5*5)=125  
(3*3*3)=27  
So:  
1+125+27=153 
Let's try to understand why 371 is an Armstrong number.
371 = (3*3*3)+(7*7*7)+(1*1*1)  
where:  
(3*3*3)=27  
(7*7*7)=343  
(1*1*1)=1  
So:  
27+343+1=371

Java Program to Check Armstrong Number

package com.javaguides.java.tutorial;

import java.util.Scanner;

/**
 * Java Program to Check Armstrong Number
 * 
 * @author https://www.javaguides.net/
 *
 */
public class JavaProgram {
    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            int temp, total = 0;
            System.out.println("√čnter 3 Digit Number : ");
            int num = scanner.nextInt();
            int number = num;

            for (; number != 0; number /= 10) {
                temp = number % 10;
                total = total + temp * temp * temp;
            }

            if (total == num) {
                System.out.println(num + " is an Armstrong number");
            } else {
                System.out.println(num + " is not an Armstrong number");
            }
        }
    }
}
Output:
√čnter 3 Digit Number : 
153
153 is an Armstrong number

Related Java Programs

Comments