Happy Word Program in Java Using Alphabet Position Values

⚡ Direct Answer & Key Takeaway

A Happy Word in ICSE Java is a word whose concatenated alphabet position values form a Happy Number. Converting each uppercase letter via `ch - 'A' + 1` maps A to 1 and Z to 26. Joining these values builds a numeric string parsed into a `long` integer. Repeatedly summing the squares of its digits reduces any Happy Number to 1, while unhappy numbers eventually enter the endless 4-16-37-58-89-145-42-20 cycle.

1. Mapping Letters to Alphabet Positions With ASCII

Every uppercase English letter occupies a contiguous ASCII block from 65 ('A') through 90 ('Z'). Instead of writing twenty-six conditional branches or a large switch statement, ICSE examiners expect clean character arithmetic. Once the user's input word is trimmed and converted with `toUpperCase()`, subtracting 64—or equivalently writing `(ch - 'A' + 1)`—yields 1 for A, 2 for B, and 22 for V. Before appending each integer onto an accumulator string, verify that `Character.isLetter(ch)` holds true so stray punctuation, spaces, or digits never corrupt the generated numeric value.

  • Uppercase 'A' has ASCII 65, so `'A' - 'A' + 1` evaluates cleanly to 1 and `'Z' - 'A' + 1` evaluates to 26.
  • Using `sc.next()` reads a single whitespace-delimited word cleanly without trailing spaces.
  • Validating `Character.isLetter(ch)` prevents non-alphabetic characters from triggering `NumberFormatException` later.

2. Avoiding Integer Overflow With Long Concatenation

Concatenating two-digit letter codes grows the resulting integer surprisingly fast during board testing. A five-letter word such as SCHOOL expands to 1938151512, which already reaches ten digits and sits near the 32-bit `int` ceiling of 2,147,483,647. Calling `Integer.parseInt()` on a slightly longer word like COMPUTER immediately throws a runtime `NumberFormatException` even though the syntax looks spotless. Storing the parsed value inside a 64-bit `long` via `Long.parseLong()` safely accommodates words up to nine or ten letters, keeping your BlueJ output reliable across diverse test cases.

  • Java `int` maxes out at 2,147,483,647 (10 digits), while `long` supports up to 9,223,372,036,854,775,807 (19 digits).
  • Concatenating into a `String` (`posStr + pos`) handles both 1-digit (1–9) and 2-digit (10–26) letter codes uniformly.
  • Printing the intermediate `Position Number` helps ICSE examiners verify your conversion logic during partial marking.

3. Digit-Square Reduction Loop for VAT and Edge Cases

Once you obtain the numeric value `num`, an outer `while (num != 1 && num != 4)` loop drives the Happy Number check cleanly. Inside it, an inner loop extracts each digit with `temp % 10`, squares it, adds the square to `sum`, and drops the last digit using `temp /= 10`. For the classic board example VAT (22, 1, 20), `num` starts at 22120, reduces to 13, then 10, and finally reaches 1. Stopping at `num != 4` also catches single-letter happy words like G (7 -> 49 -> 97 -> 130 -> 10 -> 1) that a naive `num > 9` condition misses.

  • Trace for VAT: 22120 → (4+4+1+4+0 = 13) → (1+9 = 10) → (1+0 = 1), confirming Happy Word.
  • Resetting `sum = 0` inside each outer iteration prevents old digit-square totals from carrying over.
  • Using `temp` inside the inner extraction loop keeps `num` intact until the full sum is computed.

4. BlueJ Java Program: Happy Word Check Using ASCII Letter Positions

import java.util.*;

public class HappyWord {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = sc.next().trim().toUpperCase();
        sc.close();

        String posStr = "";
        boolean valid = true;

        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (Character.isLetter(ch)) {
                int pos = ch - 'A' + 1;
                posStr = posStr + pos;
            } else {
                valid = false;
                break;
            }
        }

        if (!valid || posStr.length() == 0) {
            System.out.println("Invalid input. Enter alphabets only.");
            return;
        }

        long num = Long.parseLong(posStr);
        System.out.println("Position Number: " + num);

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

        if (num == 1) {
            System.out.println(word + " is a Happy Word.");
        } else {
            System.out.println(word + " is NOT a Happy Word.");
        }
    }
}

Verified Console / Dry-Run Output:

Enter a word: VAT
Position Number: 22120
VAT is a Happy Word.

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
wordStringStores trimmed uppercase input word (Sample: "VAT")
chcharHolds each extracted character during loop (Sample: 'V', 'A', 'T')
posStrStringConcatenates alphabet positions as text (Sample: "22120")
numlongParsed position number reduced repeatedly (22120 → 13 → 10 → 1)
sumlongAccumulates sum of squared digits per pass (13, 10, 1)
dlongExtracts individual units digit via temp % 10 (0, 2, 1, 2, 2)
🎯 1-on-1 Live Mentorship & Free Study Kit

Master ICSE String & Number Programs 1-on-1

Practice board-level ASCII conversions, dry-run tracing, and Happy Word variations live with an ICSE Java mentor in a 1-on-1 BlueJ session.

💬 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: Using int instead of long for Long.parseLong(), which throws NumberFormatException on 6-letter words whose concatenated positions exceed 2,147,483,647.
  • Avoid Mistake: Writing while (num > 9) instead of while (num != 1 && num != 4), which fails for single-digit happy numbers such as 7 (letter G).
  • Avoid Mistake: Forgetting to convert the input word to uppercase before subtracting 'A' (65), causing lowercase letters (ASCII 97–122) to produce positions 33–58.
  • Examiner / Mentor Tip: Write `pos = ch - 'A' + 1` instead of `ch - 64` or explain `'A' = 65` in comments—examiners appreciate self-documenting ASCII expressions.
  • Examiner / Mentor Tip: Include a full Variable Description Table (VDT) covering `posStr`, `num`, `temp`, `sum`, and `d` to secure full Section B documentation marks.
  • Examiner / Mentor Tip: Always state the dry-run reduction chain (22120 → 13 → 10 → 1) if asked for a sample trace or viva explanation.

7. Interactive Concept Check Quiz

Question: What value does `posStr` hold just before `Long.parseLong(posStr)` runs when the user inputs `"key"`?

8. Frequently Asked Questions

Why is VAT considered a Happy Word in ICSE Java?
For the word VAT, V sits at position 22, A at 1, and T at 20, forming 22120. Summing digit squares gives 2² + 2² + 1² + 2² + 0² = 13. Next, 1² + 3² = 10, and 1² + 0² = 1. Because the reduction reaches 1, VAT is a Happy Word in ICSE exams.
Should we use raw ASCII values like 65 or alphabet positions 1 to 26?
No, Happy Word logic requires exact letter-position concatenation (A=1 to Z=26), not raw ASCII codes (A=65 to Z=90). Subtracting 'A' - 1 (or 64) from an uppercase character converts ASCII 65 into 1 and ASCII 90 into 26. Using raw ASCII codes directly changes the formed number and produces wrong results.
Why does while (num != 1 && num != 4) work better than while (num > 9)?
Every unhappy positive integer eventually enters the eight-number cycle 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. Checking num != 1 && num != 4 stops immediately once either outcome is guaranteed, whereas num > 9 wrongly stops early on 7, which is actually a Happy Number.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class