Count Vowels, Consonants, Digits and Spaces in Java (ICSE)

⚡ Direct Answer & Key Takeaway

To classify every character in a sentence in ICSE Java, loop from `0` to `str.length() - 1` and inspect `ch = str.charAt(i)` with `java.lang.Character` wrapper methods inside a mutually exclusive `if-else if` ladder. Check `Character.isLetter(ch)` first—if true, test `"AEIOUaeiou".indexOf(ch) != -1` for **vowels**, else increment **consonants**. Next, check `Character.isDigit(ch)` for **digits**, `ch == ' '` for **spaces**, and `else` for **special characters**. This nesting guarantees digits or punctuation are never miscounted as consonants.

1. Why Consonants Need Character.isLetter() First

A classic ICSE exam trap occurs when students check for vowels and put `consonants++` inside a bare `else` branch! Doing so counts every digit (`'9'`), space (`' '`), comma, and exclamation mark as a consonant, inflating the consonant total dramatically. Instead, gate the vowel-versus-consonant decision inside `if (Character.isLetter(ch))`. Only alphabetical characters enter that block: vowels increment `vowels`, while all remaining letters fall into the inner `else` for `consonants`. Non-letters then cascade cleanly down to `Character.isDigit(ch)`, whitespace detection, and finally `specialChars`, keeping every category mutually exclusive and mathematically exact.

  • Remember `Character` belongs to `java.lang`, which is imported automatically, though `import java.util.*;` is still required for `Scanner`.
  • Test both uppercase and lowercase vowels (`"AEIOUaeiou"`) or convert `ch` with `Character.toUpperCase(ch)` before comparing.
  • Notice that `vowels + consonants + digits + spaces + specialChars` must always equal `str.length()`.

2. Using Character Class Methods vs. ASCII Ranges

ICSE Class 10 syllabi explicitly cover `Character` wrapper methods (`isLetter`, `isDigit`, `isWhitespace`, `isUpperCase`, `isLowerCase`) alongside ASCII codes (`'A'` = 65, `'a'` = 97, `'0'` = 48). While range checks like `(ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')` are valid, `Character.isLetter(ch)` and `Character.isDigit(ch)` are shorter, harder to mistype under exam pressure, and self-explanatory to evaluators. Also watch the distinction between `ch == ' '` (counts standard spaces only) and `Character.isWhitespace(ch)` (which also counts tabs `'\t'`). For standard BlueJ keyboard inputs, `ch == ' '` or `Character.isWhitespace(ch)` yields identical counts.

  • Expect Section A 2-mark questions asking the return type of `Character.isDigit('5')` (`boolean`, returning `true`).
  • Never write `Character.isDigit(48)` expecting `'0'`—pass the `char` literal `'0'`, or `48` will be treated as an ASCII code point.
  • Initialize all five integer counters (`vowels`, `consonants`, `digits`, `spaces`, `specials`) to `0` before the loop starts.

3. Verifying Counts with a Mixed-Character Sample

Suppose the user enters `"ICSE 2026: Java!"`, which contains `16` characters in total. Stepping through index `0` to `15`: the letters `I, E, a, a` tally `4` vowels, while `C, S, J, v` tally `4` consonants. Next, the year `2026` increments `digits` four times (`4`). The two blank spaces between words increment `spaces` to `2`. Finally, the colon `':'` and exclamation mark `'!'` fail letter, digit, and space checks, landing in `specials` (`2`). Summing `4 + 4 + 4 + 2 + 2 = 16` confirms zero characters were dropped or double-counted.

  • Use `sc.nextLine()` without `trim()` if leading or trailing spaces also need to be counted.
  • Print each counter on a separate labeled line so output matches CISCE sample runs cleanly.
  • Use the sum-check rule (`sum == str.length()`) during BlueJ testing to catch misplaced `else` branches immediately.

4. CharacterFrequencyCounter.java (BlueJ ICSE Solution)

import java.util.*;

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

        int vowels = 0, consonants = 0, digits = 0, spaces = 0, specials = 0;

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isLetter(ch)) {
                if ("AEIOUaeiou".indexOf(ch) != -1) {
                    vowels++;
                } else {
                    consonants++;
                }
            } else if (Character.isDigit(ch)) {
                digits++;
            } else if (ch == ' ') {
                spaces++;
            } else {
                specials++;
            }
        }

        System.out.println("Vowels             : " + vowels);
        System.out.println("Consonants         : " + consonants);
        System.out.println("Digits             : " + digits);
        System.out.println("Spaces             : " + spaces);
        System.out.println("Special Characters : " + specials);
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter a string: ICSE 2026: Java!
Vowels             : 4
Consonants         : 4
Digits             : 4
Spaces             : 2
Special Characters : 2

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

VariableData TypeExam Purpose & Sample Value
scScannerReads full input string with spaces using nextLine()
strStringHolds user input string ("ICSE 2026: Java!")
iintLoop index traversing characters from 0 to str.length() - 1
chcharCurrent character examined in each iteration ('I', '2', ':')
vowels, consonantsintCount alphabetical vowels (4) and consonants (4)
digits, spaces, specialsintCount numeric digits (4), blanks (2), and symbols (2)
🎯 1-on-1 Live Mentorship & Free Study Kit

Ace ICSE Character Wrapper & Loop Questions Live

Join a 1-on-1 BlueJ tutoring session to master Character methods, nested if-else classification, and error-free VDT writing.

💬 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: Counting consonants in an unguarded `else` after checking vowels, which wrongly classifies digits, spaces, and punctuation as consonants.
  • Avoid Mistake: Checking only uppercase vowels `"AEIOU"` without converting `str` or including `"aeiou"`, causing lowercase vowels like `'a'` and `'e'` to be miscounted as consonants.
  • Avoid Mistake: Calling `sc.next()` instead of `sc.nextLine()`, which stops at the first whitespace and always reports `spaces = 0`.
  • Examiner / Mentor Tip: Remember the return types of `Character` methods for Section A MCQs: `isLetter()`, `isDigit()`, and `isWhitespace()` all return `boolean`.
  • Examiner / Mentor Tip: If an ICSE question asks to count uppercase and lowercase letters separately, check `Character.isUpperCase(ch)` and `Character.isLowerCase(ch)` inside the `isLetter` block.
  • Examiner / Mentor Tip: Always verify your BlueJ test output by checking whether all category totals add up to `str.length()`.

7. Interactive Concept Check Quiz

Question: What will Character.isLetter('7') and Character.isDigit('7') return respectively in Java?

8. Frequently Asked Questions

How do I count vowels and consonants without counting spaces in Java?
Wrap your vowel and consonant logic inside an outer if (Character.isLetter(ch)) check. That guard blocks spaces, digits, and punctuation marks from ever reaching the consonant branch. Any character passing isLetter() that is absent from "AEIOUaeiou" is guaranteed to be a genuine alphabetical consonant in Java every time.
Is Character.isLetter() allowed in ICSE Class 10 board exams?
Yes, Character wrapper class methods—including isLetter(), isDigit(), isUpperCase(), isLowerCase(), isWhitespace(), and toUpperCase()—are explicitly prescribed in the official CISCE ICSE Class 10 Computer Applications syllabus. Board examiners award full marks for these methods, and using them cleanly prevents boundary typos common in manual ASCII comparisons.
How can I also count the number of words in the same program?
For a clean sentence separated by single spaces without leading or trailing blanks, total words equal spaces + 1. To handle uneven spacing reliably in ICSE programs, trim the input, append one space, and count positions where a non-space character sits directly before a space in the loop.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class