Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Harshad Number in Java

Test a Harshad number in Java with a digit-sum helper and n % sum. Positive inputs must divide exactly by their digit sum; guards reject zero and negatives.

IntermediateJava Loop ProgramsExample 24 of 25
harshad-number.java
1import java.util.Scanner;
2
3public class Main {
4 private static int sumOfDigits(int n) {
5 long value = Math.abs((long) n);
6 int sum = 0;
7 while (value != 0) {
8 sum += (int) (value % 10);
9 value /= 10;
10 }
11 return sum;
12 }
13
14 public static void main(String[] args) {
15 Scanner sc = new Scanner(System.in);
16 System.out.print("Enter a number: ");
17 int n = sc.nextInt();
18
19 int sum = sumOfDigits(n);
20 if (n > 0 && sum != 0 && n % sum == 0) {
21 System.out.println(n + " is a Harshad Number");
22 } else {
23 System.out.println(n + " is not a Harshad Number");
24 }
25 sc.close();
26 }
27}

Sample Output

Enter a number: 18
18 is a Harshad Number

sumOfDigits(18) adds 8 and 1 to get 9. Since 18 % 9 equals zero, the Harshad message prints.

In this one

  • Reuse a digit-sum helper
  • Protect a remainder operation from zero
  • Apply a positive-number definition

How it works

  1. 1

    Read n.

  2. 2

    Calculate sumOfDigits(n).

  3. 3

    Check positive n and a non-zero sum.

  4. 4

    Use n % sum to decide the message.

Edge cases

Zero

Enter 0

The positive-input check fails and no division by zero takes place.

Negative input

Enter -18

It is rejected because this definition applies to positive whole numbers.

What's going on

A Harshad number is a positive whole number divisible by the sum of its digits. Divisible means that the division leaves no remainder. For 18, the digit sum is 1 + 8 = 9, and 18 divides exactly by 9.

Scanner is the keyboard reader. The sumOfDigits helper repeatedly adds the last digit and removes it. The main condition first requires n > 0 and sum != 0, then checks n % sum == 0. % gives the remainder after division. The && conditions are checked left to right and stop when one is false.

The non-zero sum check prevents division by zero for input zero. This version also rejects negative numbers to match the positive-number definition. The helper uses a long working copy before removing the sign so it remains safe for every int input. Do not confuse this property with simply having an even digit sum.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the digit sum of 18?

Pick an answer to check it.

Question 2

Why does 18 pass?

Pick an answer to check it.

Questions people ask

Is 19 a Harshad number?

No. Its digit sum is 10, and 19 leaves remainder 9 when divided by 10.

Why check sum before %?

Using zero as a divisor would cause an arithmetic error.

Does every one-digit positive number qualify?

Yes. Its digit sum equals itself, so it divides exactly.