Fill your College Details

Summarise With AI
Back

Check Happy Number in Java with Code Examples

Summarise With Ai
23 Aug 2025
4 min read

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:

  • A cycle is reached, including 1 (the number is a Happy Number).
  • A cycle that does not include 1 (the number is unhappy) is reached.

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.

🎯 Calculate your GPA instantly — No formulas needed!!

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:

  • A cycle is reached, including 1 (the number is a Happy Number).
  • A cycle that does not include 1 (the number is unhappy) is reached.

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:

  • Take a number num as input.
  • Implement a function called NumHappy (), which calculates the sum of squares of the digits of num.
  • In the function is unhappy():
  • Find the last digit of num by getting the remainder when divided by 10.
  • The square of the last digit should be added to the sum.
  • Divide num by 10; do this until you finish all the digits.
  • In the main, apply the function isNumHappy() on num repeatedly until:
  • If the result is 1, the number is happy.
  • If the result is 4, the number will fall into an unhappy cycle (not happy).
  • If the final value equals to 1, print "The entered number is a Happy Number," otherwise print "The entered number is not a Happy Number."

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

  • getSumOfSquares() defined gives the number obtained from the square of the digits of the number.
  • The program continues invoking this function until its result becomes 1 or 4.
  • If the result is 1, the number is happy; however, if 4 occurs, the number is not.

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

  • This approach uses a HashSet to track the numbers encountered during the summation process and detect the presence of cycles.
  • If a number recurs, a cycle is there, making it unhappy.
  • Looping continues until 1 is achieved (happy) or a number already used (cycle) is recognised.

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

  • The program now takes a recursive approach while checking the sum of the squares of the challenged centre number.
  • It halts and returns true if the checked number becomes 1 (happy) and returns false if it becomes 4 (unhappy).
  • The recursion continues until the numbers reach either 1 or 4.d.

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

1. 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).

2. 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.

3. 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.

Summarise With Ai

Read More Articles

Chat with us
Chat with us
Talk to career expert