Extract Words and Digits Separately and Sum Digits in Java

⚡ Direct Answer & Key Takeaway

To split letters and digits from a mixed Java string, inspect each character inside a single `for` loop using `Character.isLetter(ch)` and `Character.isDigit(ch)`. Append letters and single word-separating spaces into a `words` string while collecting numeric characters into a `digits` string. Convert each digit character to its integer value with `ch - '0'` (never `(int) ch`, which returns ASCII 48–57) and accumulate the running total.

1. Classifying Characters With Character.isLetter and isDigit

Mixed strings such as `"ICSE2026 BlueJ95 Exam8!"` interleave letters, digits, spaces, and punctuation marks inside a single input line. Java's `java.lang.Character` class—imported automatically without extra statements—provides `Character.isLetter(ch)` and `Character.isDigit(ch)` to classify every character reliably. Whenever `ch` is a letter, append it directly to `words`. When `ch` is a space and `words` is non-empty without a trailing space, append one separator space so extracted words remain readable rather than fusing into one continuous token like `"ICSEBlueJExam"`.

  • `Character.isLetter(ch)` matches both uppercase and lowercase alphabets without manual ASCII range checks.
  • Checking `!words.endsWith(" ")` prevents duplicate spaces when digits or symbols sit between words.
  • `Character.isDigit(ch)` accurately isolates `'0'` through `'9'` for both string extraction and summation.

2. Converting Digit Characters to Numeric Values Safely

One of the most frequent Section A and B traps in ICSE Java is writing `sum += (int) ch;` for a digit `char`. Because `'0'` through `'9'` occupy ASCII codes `48` through `57`, casting `'5'` adds `53` instead of `5`! Subtracting `'0'` (`ch - '0'`) or calling `Character.getNumericValue(ch)` converts `'5'` accurately to `5`. Meanwhile, concatenating `ch` onto a `digits` string preserves the exact sequence `"2026958"` even when leading zeros appear inside the input, avoiding integer parsing errors if no digits exist at all.

  • ASCII table reference: `'0'` = 48, `'1'` = 49, ..., `'9'` = 57.
  • For `"ICSE2026 BlueJ95 Exam8!"`, `digitSum` evaluates to `2+0+2+6+9+5+8 = 32`.
  • Storing `digits` as a `String` keeps leading zeros intact and never overflows `int` limits.

3. Handling Special Symbols and Zero-Digit Edge Cases

Real user inputs often contain punctuation marks such as `!`, `@`, or `-`, as well as edge-case strings containing zero digits or zero letters. Routing leftover characters outside the `isLetter`, `isDigit`, and whitespace branches (or counting them in an optional `specialCount` variable) prevents stray symbols from leaking into your extracted words. Before printing final output, call `words.trim()` and check `digits.isEmpty()` so an all-alphabet sentence displays `"None"` and a digit sum of `0` cleanly instead of confusing blank lines.

  • `words.trim()` removes any trailing space left before end-of-line digits or punctuation.
  • Ternary checks (`digits.isEmpty() ? "None" : digits`) make console output clear on edge-case inputs.
  • Adding an `else` counter easily adapts this code to ICSE questions asking for special character counts too.

4. BlueJ Java Program: Separate Words & Digits and Sum Digits

import java.util.*;

public class ExtractWordsAndDigits {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a mixed string: ");
        String input = sc.nextLine();
        sc.close();

        String words = "";
        String digits = "";
        int digitSum = 0;

        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (Character.isLetter(ch)) {
                words += ch;
            } else if (Character.isDigit(ch)) {
                digits += ch;
                digitSum += (ch - '0');
            } else if (ch == ' ' && !words.isEmpty() && !words.endsWith(" ")) {
                words += ' ';
            }
        }

        words = words.trim();
        System.out.println("Extracted Words: " + (words.isEmpty() ? "None" : words));
        System.out.println("Extracted Digits: " + (digits.isEmpty() ? "None" : digits));
        System.out.println("Sum of Digits: " + digitSum);
    }
}

Verified Console / Dry-Run Output:

Enter a mixed string: ICSE2026 BlueJ95 Exam8!
Extracted Words: ICSE BlueJ Exam
Extracted Digits: 2026958
Sum of Digits: 32

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

VariableData TypeExam Purpose & Sample Value
inputStringStores original mixed input string (Sample: "ICSE2026 BlueJ95 Exam8!")
wordsStringCollects extracted alphabetic words (Sample: "ICSE BlueJ Exam")
digitsStringCollects extracted numeric characters in order (Sample: "2026958")
digitSumintAccumulates numeric sum via ch - '0' (Sample: 32)
chcharCurrent character checked at position i (Sample: 'I', '2', '!')
iintLoop counter running from 0 to input.length() - 1 (Sample: 0..22)
🎯 1-on-1 Live Mentorship & Free Study Kit

Master Character Class & String Parsing Live

Practice Character wrapper methods, ASCII digit math, and mixed-string parsing live with an ICSE Computer Applications mentor.

💬 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: Writing `digitSum += (int) ch;` which adds ASCII 48–57 instead of 0–9, inflating the sum by 48 per digit.
  • Avoid Mistake: Concatenating letters without preserving spaces between tokens, turning `"ICSE2026 BlueJ95"` into `"ICSEBlueJ"`.
  • Avoid Mistake: Trying to call `Integer.parseInt(digits)` to sum digits when the input contains no digits (`""`) or more than 10 digits, causing runtime exceptions.
  • Examiner / Mentor Tip: Quote the exact ASCII range `'0'` = 48 to `'9'` = 57 in viva answers to explain why `ch - '0'` is needed.
  • Examiner / Mentor Tip: Always verify whether the question wants the sum of individual digits (`2+0+2+6 = 10`) or full multi-digit numbers (`2026`).
  • Examiner / Mentor Tip: Include both `words` and `digits` edge-case checks (`isEmpty()`) in your dry run to impress ICSE examiners.

7. Interactive Concept Check Quiz

Question: If a student accidentally writes `digitSum += ch;` instead of `digitSum += (ch - '0');`, what will `digitSum` equal for `"A4B9"`?

8. Frequently Asked Questions

Why does `(int) ch` give the wrong sum for digit characters in Java?
In Java, casting a digit `char` like `'4'` with `(int) ch` returns its ASCII code `52` rather than `4`. Subtracting `'0'` (ASCII 48) computes `52 - 48 = 4`. Alternatively, `Character.getNumericValue(ch)` gives the exact same integer value cleanly.
What if the mixed string has zero digits or too many digits for `int`?
You do not need `parseInt` at all to sum individual digits—accumulating `(ch - '0')` character by character works even if the string has 50 digits or zero digits. Keep `digits` as a `String` so leading zeros like `007` are never lost during output.
How does this program keep words separated without extra spaces?
When an uppercase or lowercase letter appears, it enters `words`. When a space appears after at least one word and `words` does not already end with a space, one space is kept. Digits and symbols are skipped in `words`, leaving clean space-separated words.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class