Home / Programs / Java Program to Check Happy Number
Programming Example

Java Program to Check Happy Number

👁 91 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

Given Input:

Enter a number to check if it's a Happy Number: 19

Expected Output:

19 is a Happy Number!

Program Code

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

public class HappyNumberChecker {

    // Function to calculate the sum of squares of digits
    public static int sumOfSquares(int number) {
        int sum = 0, digit;
        while (number > 0) {
            digit = number % 10; // Extract the last digit
            sum += digit * digit; // Add the square of the digit
            number /= 10; // Remove the last digit
        }
        return sum;
    }

    // Function to check if a number is a Happy Number
    public static boolean isHappyNumber(int number) {
        HashSet<Integer> seenNumbers = new HashSet<>();
        
        while (number != 1 && !seenNumbers.contains(number)) {
            seenNumbers.add(number); // Track visited numbers
            number = sumOfSquares(number); // Update the number
        }
        
        return number == 1; // Return true if it reaches 1
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number to check if it's a Happy Number: ");
        int number = scanner.nextInt();

        if (isHappyNumber(number)) {
            System.out.println(number + " is a Happy Number!");
        } else {
            System.out.println(number + " is NOT a Happy Number.");
        }

        scanner.close();
    }
}

Output

Enter a number to check if it's a Happy Number: 20
20 is NOT a Happy Number.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.