How to check whether a number is an Armstrong number or not in java?

A special positive number whose sum of cubes of its individual digit is equal to that number is called an Armstrong Number

Example #1,
The number 153 is an Armstrong number. It can be checked as follow:
(1)3 + (5)3 + (3)3 => 1 + 125 + 27 => 153

Example #2,
The number 371 is also an Armstrong number and It can be checked as follow:
(3)3 + (7)3 + (1)3 => 27 + 343 + 1 => 371

Let’s see the logic to check whether a number is an Armstrong number or not,

Armstrong number in java

ArmstrongNumber.java

package com.javacodepoint.programs;

import java.util.Scanner;

public class ArmstrongNumber {

	public static void main(String[] args) {
		
		// Taking input from the user to check whether number is Armstrong

		System.out.println("Enter a number to check Armstrong :");

		// Reading user input using Scanner object
		int number = new Scanner(System.in).nextInt();
		
		if(checkArmstrong(number)) {
			System.out.println("The given number is an Armstrong number.");
		}else {
			System.out.println("The given number is not an Armstrong number.");
		}
		
	}
	
	/*
	 * Method to check Armstrong number
	 */
	public static boolean checkArmstrong(int number) {
	    
		int sumOfCube = 0;
		int temp = number;    
	    while(number > 0){
	    	
	    	//Getting last digit 
	        int a = number % 10;  
	        
	        //Removing last digit from number  
	        number = number / 10;  
	        
	        //Calculating sum of cubes of digits    
	        sumOfCube = sumOfCube + (a*a*a); 
	    } 
	    
	    if(temp == sumOfCube) {
	    	return true;
	    }
	    
	    return false;
	}

}

OUTPUT:

Enter a number to check Armstrong :
370
The given number is an Armstrong number.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework