Write a Java program to check if a number is Armstrong or not ?

Armstrong number Example in Java

How to check if a number is Armstrong number or not? or write a Java program to find Armstrong number? This is a common Java interview question asked on campus interviews and fresher level interviews. This is also a popular Java programming exercise on various school, colleges and computer courses to build programming logic among Students. An Armstrong number is a 3 digit number for which sum of cube of its digits is equal to the number itself. An example of Armstrong number is 153 as 153= 1+ 125+27 which is equal to 1^3+5^3+3^3. One more example of the Armstrong number is 371 because it is the sum of 27 + 343 + 1 which is equal to 3^3 + 7^3 + 1^3 . In this Java program example, we will see complete code example of Java program to check if any 3 digit number is Armstrong number or not. If you are going for Java interview, then be prepare for some follow-up questions e.g. finding prime numbers, or finding Armstrong number of more than 3 digits.

Java Program to Find Armstrong Number

import java.util.Scanner;
public class ArmstrongTest{

    
    public static void main(String args[]) {
    
        //input number to check if its Armstrong number
        System.out.println("Please enter a 3 digit number to find if 
                                  its an Armstrong number:");
        int number = new Scanner(System.in).nextInt();
      
        //printing result
        if(isArmStrong(number)){
            System.out.println("Number : " + number + " is an Armstrong number");
        }else{
            System.out.println("Number : " + number + " is not an Armstrong number");
        }

    
    }

    /*
     * @return true if number is Armstrong number or return false
     */
    private static boolean isArmStrong(int number) {
        int result = 0;
        int orig = number;
        while(number != 0){
            int remainder = number%10;
            result = result + remainder*remainder*remainder;
            number = number/10;
        }
        //number is Armstrong return true
        if(orig == result){
            return true;
        }
      
        return false;
    } 
  
}
Output:
Please enter a 3 digit number to find if its an Armstrong number:
153
Number : 153 is an Armstrong number
Please enter a 3 digit number to find if its an Armstrong number:
153
Number : 153 is an Armstrong number
Please enter a 3 digit number to find if its an Armstrong number:
371
Number : 371 is an Armstrong number