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

Java Program to Check Happy Number

👁 91 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

📌 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();
    }
}

                        

🖥 Program Output

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

                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.