Happy Number Program in Java BlueJ

⚑ Direct Answer & Key Takeaway

A Happy Number is a positive integer that eventually reduces to 1 when repeatedly replaced by the sum of the squares of its digits. Any unhappy integer enters an endless cycle containing 4, such as 4, 16, 37, 58, 89, 145, 42, and 20. In Java BlueJ, an outer while loop repeats digit squaring inside an inner loop until the value becomes 1 or 4. If the final value equals 1, the input is a Happy Number.

1. Why 1 and 4 Terminate the Happy Loop

Every positive integer subjected to repeated digit-squaring follows one of two deterministic paths. Either the sequence converges to 1, classifying the starting integer as a Happy Number, or it falls into a closed eight-number cycle anchored at 4: 4, 16, 37, 58, 89, 145, 42, and back to 4. Because every multi-digit number shrinks rapidly under digit squaringβ€”even 999 drops to 243 in one stepβ€”no positive integer can grow without bound. Recognizing 4 as the universal trap sentinel saves students from guessing arbitrary iteration caps or writing infinite loops. Notice also that single-digit numbers 1 and 7 are the only digits under 10 that eventually land on 1, whereas 2, 3, 4, 5, 6, 8, and 9 all merge into the 4-cycle. In CISCE board evaluations, testing temp != 1 && temp != 4 inside the outer while condition demonstrates clear mathematical reasoning and guarantees termination for every valid positive integer.

  • Happy convergence target: stop as soon as temp equals 1.
  • Cycle sentinel: stop immediately when temp equals 4 to prevent an infinite loop.
  • Single-digit Happy Numbers: only 1 and 7 terminate at 1.

2. Step-by-Step Dry Run for 19 and 20

Tracing both an accepted and a rejected input reveals exactly how the outer and inner loops cooperate during execution. Take num = 19, so temp starts at 19. Pass 1 extracts 9 (19 % 10) and 1 (1 / 10), accumulating sum = 81 + 1 = 82, then assigns temp = 82. Pass 2 yields 2^2 + 8^2 = 68, setting temp = 68. Pass 3 computes 8^2 + 6^2 = 100, assigning temp = 100. Pass 4 evaluates 0^2 + 0^2 + 1^2 = 1, which fails temp != 1 and prints Happy Number. Now contrast num = 20: Pass 1 produces 0^2 + 2^2 = 4. Immediately, temp != 4 becomes false, ending the outer loop in a single pass and reporting Not a Happy Number. Recording each temp and sum transition in a neat margin table earns full dry-run credit in BlueJ practicals.

  • Input 19 trace: 19 -> 82 -> 68 -> 100 -> 1 (Happy Number in 4 passes).
  • Input 20 trace: 20 -> 4 (Not a Happy Number in 1 pass).
  • Input 7 trace: 7 -> 49 -> 97 -> 130 -> 10 -> 1 (requires 5 passes).

3. Nested While Loop Design in BlueJ

Structuring the solution with two while loops separates digit extraction from sequence tracking, keeping BlueJ code readable under timed exam conditions. Before entering the outer loop, validate that num > 0, because zero or negative values would violate the temp != 1 && temp != 4 guard or skip the inner extraction loop entirely. Inside the outer loop, resetting sum = 0 on every pass is mandatory; forgetting that single reset carries the prior iteration's total forward and corrupts every subsequent step. The inner loop consumes temp via temp % 10 and temp /= 10 until temp hits 0, after which temp = sum hands the new candidate back to the outer loop. Finally, close the Scanner object before main exits so BlueJ's terminal window remains free of resource-leak warnings and preserves clean coding style marks.

  • Copy num into temp before looping so the original input stays intact for printing.
  • Reset sum = 0 inside the outer loop before the inner digit loop begins.
  • Guard against num <= 0 at the start to handle invalid inputs gracefully.

4. HappyNumber.java (BlueJ)

import java.util.Scanner;

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

        if (num <= 0) {
            System.out.println(num + " is not a Happy Number.");
            sc.close();
            return;
        }

        int temp = num;
        while (temp != 1 && temp != 4) {
            int sum = 0;
            while (temp > 0) {
                int digit = temp % 10;
                sum += digit * digit;
                temp /= 10;
            }
            temp = sum;
        }

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

Verified Console / Dry-Run Output:

Enter a positive integer: 19
19 is a Happy Number.

Enter a positive integer: 20
20 is not a Happy Number.

5. Variable Description Table (VDT) β€” HappyNumber

Variable NameData TypePurpose in Program
scScannerReads the integer input from the user via standard input
numintStores the original positive integer entered by the user
tempintHolds the working value reduced in each outer-loop pass
sumintAccumulates the sum of squares of digits in each pass
digitintExtracts the rightmost digit using modulo 10
🎯 1-on-1 Live Mentorship & Free Study Kit

Master ICSE Java Loops with 4Achievers Junior

Practice nested loop tracing and live BlueJ debugging in 1-on-1 or 1:4 Micro-Pods with IIT/NIT mentors at 4Achievers Junior (Grades 3-12).

πŸ’¬ WhatsApp Now
πŸ”’ Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Forgetting to reset sum = 0 at the start of every outer while iteration, which inflates subsequent totals.
  • Avoid Mistake: Using only temp != 1 as the loop condition without stopping at 4, causing an infinite loop on unhappy numbers.
  • Avoid Mistake: Mutating num directly instead of copying it into temp, which loses the original number for the final output message.
  • Examiner / Mentor Tip: Examiners often ask what happens if 7 or 10 is tested; remember both reduce to 1 and are valid Happy Numbers.
  • Examiner / Mentor Tip: Always include a Variable Description Table (VDT) covering sc, num, temp, sum, and digit right after your code in Section B answers.
  • Examiner / Mentor Tip: If a board question asks for Happy Numbers in a range, move the outer loop logic into a boolean isHappy(int n) helper method.

7. Interactive Concept Check Quiz

Question: Which of the following numbers is a Happy Number that eventually reduces to 1?

8. Frequently Asked Questions

Can an unhappy number ever bypass 4 and loop somewhere else?
No. Every non-happy positive integer reaches 4 within a finite number of steps and remains trapped in the 4-16-37-58-89-145-42-20 cycle, so checking temp != 1 && temp != 4 always terminates.
Why shouldn't the outer loop stop as soon as temp becomes a single digit?
Because 7 leads to 49, then 97, 130, 10, and finally 1, so 7 is actually a Happy Number. Stopping at temp > 9 would misclassify 7 and miss numbers like 19 that drop through 100 to 1.
Is 0 or any negative integer considered a Happy Number in ICSE exams?
No. Happy Numbers are defined only for positive integers (1, 7, 10, 13, 19, ...). Checking num <= 0 up front prevents incorrect loop behavior on 0 or negative inputs.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class