Harshad Number / Niven Number in Java — Definition, Examples, and Program

Learn everything about Harshad (Niven) Numbers in Java. This blog explains what a Harshad number is, how it works, real examples, properties, and a clean Java program to check whether a number is Harshad. Includes practice challenges to strengthen your understanding.

Harshad (Niven) Number in Java

A Harshad Number (also known as a Niven Number) is an integer that is divisible by the sum of its digits. These numbers are commonly asked in coding tests, Java assignments, and DSA fundamentals.

What is a Harshad (Niven) Number?

A number is called a Harshad Number if:

Number % (Sum of its digits) == 0

In simple words, if the number is perfectly divisible by the sum of its digits, then it is a Harshad Number.

Examples

  • 18: sum of digits = 1 + 8 = 9
    18 % 9 = 0 → ✔️ Harshad Number
  • 21: sum of digits = 2 + 1 = 3
    21 % 3 = 0 → ✔️ Harshad Number
  • 19: sum of digits = 1 + 9 = 10
    19 % 10 = 9 → ❌ Not a Harshad Number

Java Program to Check Harshad Number

Below is the Java program. The logic is simple:

  1. Extract digits of the number
  2. Find the sum of digits
  3. Check divisibility
public class HarshadNumber {

    public static void main(String[] args) {
        int num = 18; // Change this value to test other numbers
        int temp = num;
        int sum = 0;

        while (temp > 0) {
            sum += temp % 10;
            temp /= 10;
        }

        if (num % sum == 0) {
            System.out.println(num + " is a Harshad Number.");
        } else {
            System.out.println(num + " is NOT a Harshad Number.");
        }
    }
}
    

Properties of Harshad Numbers

  • All single-digit numbers (1–9) are Harshad Numbers.
  • 10, 12, 18, 20, 21, 24 are all Harshad Numbers.
  • Not all Harshad numbers are prime or composite — it's independent.

Practice Challenges

Challenge 1:

Write a Java program to print all Harshad numbers between 1 and 200.

Challenge 2:

Check whether a number is a Harshad number in any given base (base 2 to base 10).

Challenge 3:

Write a program to find the next Harshad number after a given number.