Check Happy Number in Java with Code Examples

Published: 23 Aug 2025 | Reading Time: 4 min read

Introduction

Happy Numbers in Java when a number repeatedly replaces itself with the sum of the squares of its digits, which eventually leads to 1. Unhappy numbers lead to a cycle that does not include 1. It is used in Java to practice number manipulation, iteration, and cycle detection. Understanding recursion, iteration, and some basic mathematical operations in programming serves one well in Happy Numbers, which provides good examples of using hash sets and detector cycles, a building block in algorithm design.

What is a Happy Number?

A Happy Number is a number that is defined to eventually lead to 1 when repeatedly replaced by the sum of the squares of its digits. The number is unhappy if this process leads to an infinite loop other than 1.

To check whether a number is happy, keep replacing the number with the sum of the squares of its digits, do this process until we obtain the final number:

Examples

Here are a few examples of happy numbers:

Example 1: Let's check whether 49 is a happy number

49 → (4² + 9²) = 16 + 81 = 97
97 → (9² + 7²) = 81 + 49 = 130
130 → (1² + 3² + 0²) = 1 + 9 + 0 = 10
10 → (1² + 0²) = 1 + 0 = 1

Since we reached 1, 49 is considered a happy number.

Example 2: Let's check whether 320 is a happy number

320 → (3² +2² + 0²) = 9 +4 + 0 =13
13 →  (1² + 3²) = 1 + 9 = 10
10 → (1² + 0²) = 1 + 0 = 1

Since we reached 1, 320 is considered a happy number.

Example 3: Let's check if 19 is a happy number or not

19 →  (1² + 9²) = 1 + 81 = 82
82 → (8² + 2²) = 64 + 4 = 68
68 → (6² + 8²) = 36 + 64 = 100
100 → (1² + 0² + 0²) = 1 + 0 + 0 = 1

Since we reached 1, 19 is considered a happy number.

What is a happy number in Java?

A happy number in Java is the number which, when repeatedly being replaced by the sum of the squares of its digits, reaches 1. If the number falls into a cycle without reaching 1, it is unhappy.

Algorithm

An algorithm to check if a number is Happy:

Implementation of Happy Number Program in Java

Here are the different Java programs for checking if a number is a happy number or not:

1. Simple Iterative Approach

This is an iterative one but based on recursion. Recursively in a recursive solution, repeatedly the sum of squares of the digits of a number is calculated.

Java Code

import java.util.Scanner;

public class HappyNumber {

    public static int getSumOfSquares(int num) {
        int sum = 0;
        while (num > 0) {
            int rem = num % 10;
            sum += rem * rem;
            num = num / 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        int result = num;
        while (result != 1 && result != 4) {
            result = getSumOfSquares(result);
        }

        if (result == 1) {
            System.out.println(num + " is a Happy Number");
        } else {
            System.out.println(num + " is not a Happy Number");
        }
    }
}

Explanation

Output

Enter a number: 19
19 is a Happy Number

Time Complexity: O(log N)

Space Complexity: O(1)

2. Using a Set to Detect Cycles

We trace all the numbers being generated by the sum of squares of digits process through a HashSet. This assists us in ascertaining if a number has been generated or not and if the whole process is in a cycle.

Java Code

import java.util.HashSet;
import java.util.Scanner;

public class HappyNumberWithSet {

    public static int getSumOfSquares(int num) {
        int sum = 0;
        while (num > 0) {
            int rem = num % 10;
            sum += rem * rem;
            num = num / 10;
        }
        return sum;
    }

    public static boolean isHappy(int num) {
        HashSet<Integer> seenNumbers = new HashSet<>();
        while (num != 1 && !seenNumbers.contains(num)) {
            seenNumbers.add(num);
            num = getSumOfSquares(num);
        }
        return num == 1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        if (isHappy(num)) {
            System.out.println(num + " is a Happy Number");
        } else {
            System.out.println(num + " is not a Happy Number");
        }
    }
}

Explanation

Output

Enter a number: 23
23 is a Happy Number

Time Complexity: O(log N)

Space Complexity: O(k)

3. Using Recursion

This is the same as the iterative solution, but loops have been replaced by recursion in this case. Recursive procedures call recursively to calculate the sum of squares of the digits of the number.

Java Code

import java.util.Scanner;

public class HappyNumberRecursive {

    public static int getSumOfSquares(int num) {
        int sum = 0;
        while (num > 0) {
            int rem = num % 10;
            sum += rem * rem;
            num = num / 10;
        }
        return sum;
    }

    public static boolean isHappy(int num) {
        if (num == 1) return true;
        if (num == 4) return false;
        return isHappy(getSumOfSquares(num));
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        if (isHappy(num)) {
            System.out.println(num + " is a Happy Number");
        } else {
            System.out.println(num + " is not a Happy Number");
        }
    }
}

Explanation

Output

Enter a number: 12
12 is not a Happy Number

Time Complexity: O(log N)

Space Complexity: O(log N)

Conclusion

In conclusion, Happy Number in Java is a number that eventually reaches 1 after repeated replacements with the sum of the squares of its digits. It is said to be unhappy if it falls into a cycle that does not include 1. We have employed three methods to solve this problem: the iterative method, which uses a set for cycle detection and a recursive process. Each method has its pros, such as simple iterate and recursive calculations and a more potent form of cycle detection using a set. By utilizing these, one method is preferable for solving the efficient query of whether a number is happy or not.

Frequently Asked Questions

Why 7 is a happy number?

7 is a happy number because repeatedly squaring and summing its digits will eventually lead to 1 (7 → 49 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 → 1).

Is 58 a happy number?

No, it is unhappy. The squared sums 58 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 fall into cycles without arriving at 1.

What is the formula for a happy number?

The formula for happy numbers replaces the original number with the sum of the squares of its digits. The algorithm continues until the number becomes unity or is lost in cycles.


Source: NxtWave - CCBP Blog