Frequency of Each Alphabet (A–Z) and Histogram in Java

⚡ Direct Answer & Key Takeaway

To count the frequency of every alphabet A–Z in a Java string, normalize the text with `toUpperCase()` and allocate an `int` array of size 26 initialized to zero. Iterate through each character: whenever `ch >= 'A' && ch <= 'Z'`, increment `freq[ch - 'A']` by one. This single-pass mapping places A at index 0 and Z at index 25, letting you print alphabetical counts and star histograms in O(n) time.

1. Mapping Uppercase Characters to Array Indices 0–25

Java automatically initializes every element of `new int[26]` to zero, giving you ready-made counters for all twenty-six letters of the English alphabet. By subtracting `'A'` (ASCII 65) from an uppercase character `ch`, `'A' - 'A'` resolves to `0`, `'B' - 'A'` resolves to `1`, and `'Z' - 'A'` resolves to `25`. Guarding the increment with `if (ch >= 'A' && ch <= 'Z')` is critical: without that range check, spaces (ASCII 32) or digits (ASCII 48–57) evaluate to negative indices and crash the program immediately with `ArrayIndexOutOfBoundsException`.

  • `new int[26]` starts with 26 zeros automatically—no manual initialization loop is needed.
  • `ch - 'A'` acts as a zero-based hash mapping `'A'..'Z'` to `0..25`.
  • Range check `ch >= 'A' && ch <= 'Z'` filters out digits, spaces, and symbols safely.

2. Why a Frequency Array Beats Nested Character Loops

Beginners often write an outer loop from `'A'` to `'Z'` and an inner loop scanning the entire string twenty-six separate times. While that nested approach still executes acceptably on short sentences, it performs 26 × N comparisons and forces repeated `charAt()` calls. Using a 26-slot `freq` array touches each input character only once during counting, then performs a tiny fixed 26-iteration pass to display results. ICSE examiners reward this combined array-and-string design because it proves mastery of both Class 9 and Class 10 syllabus pillars simultaneously.

  • Counting takes O(n) single-pass traversal regardless of alphabet distribution.
  • Output is naturally sorted alphabetically from `'A'` to `'Z'` because array indices run `0` to `25`.
  • Easily extends to finding the most frequent letter by tracking the maximum inside `freq`.

3. Printing Alphabetical Tables and Star Histograms Cleanly

Once counting completes, iterate `i` from `0` to `25` and check `if (freq[i] > 0)` so letters absent from the sentence do not clutter the console. Reconstruct the corresponding uppercase character using `(char) ('A' + i)` and display its numeric frequency alongside a row of asterisks (`*`) generated by an inner loop running `freq[i]` times. Formatting output with `\t` tab columns keeps numbers and visual histogram bars neatly aligned inside BlueJ's terminal window regardless of individual letter spacing or single- vs double-digit counts.

  • `(char) ('A' + i)` reverses the index subtraction back into a printable letter.
  • Filtering `freq[i] > 0` displays only letters that actually appeared in the input.
  • Adding `System.out.print("*")` inside a `freq[i]` loop prints an instant text histogram.

4. BlueJ Java Program: A–Z Frequency Counter & Star Histogram

import java.util.*;

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

        int[] freq = new int[26];

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch >= 'A' && ch <= 'Z') {
                freq[ch - 'A']++;
            }
        }

        System.out.println("Letter\tCount\tHistogram");
        for (int i = 0; i < 26; i++) {
            if (freq[i] > 0) {
                char letter = (char) ('A' + i);
                System.out.print(letter + "\t" + freq[i] + "\t");
                for (int j = 0; j < freq[i]; j++) {
                    System.out.print("*");
                }
                System.out.println();
            }
        }
    }
}

Verified Console / Dry-Run Output:

Enter a string: BANANA Republic 2026
Letter	Count	Histogram
A	3	***
B	2	**
C	1	*
E	1	*
I	1	*
L	1	*
N	2	**
P	1	*
R	1	*
U	1	*

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

VariableData TypeExam Purpose & Sample Value
strStringStores uppercase input sentence (Sample: "BANANA REPUBLIC 2026")
freqint[]26-element array storing counts for A–Z (freq[0]=3, freq[1]=2)
chcharCurrent character inspected in counting loop (Sample: 'B', 'A', ' ')
iintIndex for string scan and A–Z output loop (0 to 25)
lettercharReconstructed alphabet (char)('A' + i) when freq[i] > 0 (Sample: 'A')
jintInner loop counter printing asterisks for histogram (0 to freq[i]-1)
🎯 1-on-1 Live Mentorship & Free Study Kit

Combine Java Arrays & Strings Effortlessly Live

Master 1D frequency arrays, ASCII index mapping, and histogram formatting with guided BlueJ practice for ICSE Class 10.

💬 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 `freq[ch]++` without subtracting `'A'`, which throws `ArrayIndexOutOfBoundsException` because `'A'` is 65 and the array size is 26.
  • Avoid Mistake: Omitting the `if (ch >= 'A' && ch <= 'Z')` guard, causing spaces (ASCII 32, index -33) or digits (index -17 to -8) to crash the program.
  • Avoid Mistake: Printing all 26 rows including letters with zero occurrences when the question asks only for present characters.
  • Examiner / Mentor Tip: Always declare `int[] freq = new int[26];` and note in your VDT that Java auto-initializes integer arrays to 0.
  • Examiner / Mentor Tip: Remember the explicit `(char)` cast in `(char) ('A' + i)`—without it, Java prints ASCII integers like 65 instead of `'A'`.
  • Examiner / Mentor Tip: Check if your board question expects only counts or a histogram; you can omit the inner `*` loop if only tabular counts are asked.

7. Interactive Concept Check Quiz

Question: In `int[] freq = new int[26]`, which index is incremented when `ch` equals `'M'` (ASCII 77)?

8. Frequently Asked Questions

Why do we write `freq[ch - 'A']++` instead of `freq[ch]++`?
Java allocates index 0 to 25 for an array of length 26. Subtracting 'A' (65) shifts ASCII codes 65–90 down to 0–25 so 'A' updates `freq[0]` and 'Z' updates `freq[25]`. Without `- 'A'`, even `'A'` would go out of bounds.
Does converting to uppercase count both capital and small letters together?
Yes, calling `toUpperCase()` merges `'a'` and `'A'` into the same counter slot `'A'` (index 0), which standard ICSE alphabet-frequency questions expect. If a question asks for separate uppercase and lowercase counts, skip `toUpperCase()` and use a 52-element array or ASCII range check.
Can we solve alphabet frequency in ICSE Java without using an array?
Replace the `int[] freq = new int[26]` array with an outer loop `for (char alpha = 'A'; alpha <= 'Z'; alpha++)` and an inner loop counting matches in `str`. The array method is faster (single pass) and keeps your code clean while demonstrating 1D arrays.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class