Anagram Strings Checker Program in Java (BlueJ ICSE)

⚡ Direct Answer & Key Takeaway

Two strings are anagrams if they contain identical letters with identical frequencies in any order, such as `"Listen"` and `"Silent"`. In ICSE Java, normalize both strings with `toUpperCase()`, strip spaces if needed, and check whether their lengths match first. Next, either sort both `char[]` arrays via `Arrays.sort()` and compare with `Arrays.equals()`, or track letter counts in a 26-slot `int[]` array and verify every slot equals zero.

1. Length Gate & Case Normalization Before Comparison

Direct equality checks fail on classic ICSE anagram pairs such as `"Listen"` and `"Silent"` or `"Dormitory"` and `"Dirty Room"` because letter order, capitalization, and spacing differ. Start by normalizing both inputs with `replace(" ", "").toUpperCase()`. Immediately compare `a.length() != b.length()`: whenever lengths differ, an anagram is mathematically impossible and `isAnagram` becomes `false` without scanning a single character. Remember that equal length is necessary but never sufficient—strings like `"aab"` and `"abb"` share length `3` yet have mismatched letter counts.

  • Case normalization ensures 'L' in "Listen" matches 'l' in "Silent".
  • Stripping spaces lets phrase anagrams like "Astronomer" and "Moon starer" pass accurately.
  • Length mismatch (a.length() != b.length()) disqualifies non-anagrams immediately before looping.

2. Frequency Array Method vs. Character Sorting

Two clean solutions earn full marks in ICSE Class 10. The 26-element `int[] freq` approach increments `freq[c1 - 'A']` for the first string and decrements `freq[c2 - 'A']` for the second in a single loop, then verifies that every slot from `0` to `25` returned to `0`. Alternatively, converting both strings via `toCharArray()`, sorting both arrays with `Arrays.sort()`, and checking `Arrays.equals(a1, a2)` arranges `"LISTEN"` and `"SILENT"` into identical `['E','I','L','N','S','T']` sequences. Frequency counting showcases manual array indexing, while sorting handles digits and punctuation automatically.

  • Frequency counting uses int[] freq = new int[26] mapped via ch - 'A' (indices 0 to 25).
  • Incrementing for string a and decrementing for string b balances counts in a single pass.
  • Arrays.sort() turns both "silent" and "listen" into identical sorted character arrays.
  • Checking c1 >= 'A' && c1 <= 'Z' prevents negative or out-of-bounds indices on symbols.

3. Dry Run Verification & Duplicate-Letter Traps

Tracing `"LISTEN"` and `"SILENT"` through `freq` highlights why duplicate-letter traps fail cleanly. At `i = 0`, `'L'` increments `freq[11]` to `+1` while `'S'` decrements `freq[18]` to `-1`. As the remaining indices (`'I','S','T','E','N'` vs `'I','L','E','N','T'`) finish, every matching pair cancels out to `0`, leaving `isAnagram` as `true`. Now trace `"APPLE"` against `"APLEE"`: `'P'` increments twice (`+2`) in `a` but decrements once (`-1`) in `b`, leaving `freq['P' - 'A'] = +1` and `freq['E' - 'A'] = -1`, which immediately triggers `isAnagram = false`.

  • Never rely on indexOf() alone—it fails whenever characters repeat at different frequencies.
  • A boolean flag isAnagram = true lets the validation loop break on the first non-zero slot.
  • Both frequency counting and sorting handle repeated characters accurately without false positives.

4. AnagramChecker.java — Frequency Array ICSE Solution

import java.util.*;

public class AnagramChecker {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter first string : ");
        String s1 = sc.nextLine();
        System.out.print("Enter second string: ");
        String s2 = sc.nextLine();

        String a = s1.replace(" ", "").toUpperCase();
        String b = s2.replace(" ", "").toUpperCase();

        boolean isAnagram = true;

        if (a.length() != b.length()) {
            isAnagram = false;
        } else {
            int[] freq = new int[26];
            for (int i = 0; i < a.length(); i++) {
                char c1 = a.charAt(i);
                char c2 = b.charAt(i);
                if (c1 >= 'A' && c1 <= 'Z' && c2 >= 'A' && c2 <= 'Z') {
                    freq[c1 - 'A']++;
                    freq[c2 - 'A']--;
                } else {
                    isAnagram = false;
                    break;
                }
            }
            if (isAnagram) {
                for (int j = 0; j < 26; j++) {
                    if (freq[j] != 0) {
                        isAnagram = false;
                        break;
                    }
                }
            }
        }

        if (isAnagram) {
            System.out.println("\"" + s1 + "\" and \"" + s2 + "\" are Anagram Strings.");
        } else {
            System.out.println("\"" + s1 + "\" and \"" + s2 + "\" are NOT Anagram Strings.");
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter first string : Listen
Enter second string: Silent
"Listen" and "Silent" are Anagram Strings.

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

VariableData TypeExam Purpose & Sample Value
s1, s2StringStore raw input words or phrases; sample: "Listen" and "Silent"
a, bStringSpace-free uppercase normalized strings; "LISTEN" and "SILENT"
freqint[]26-slot array tracking A–Z net counts; all slots end at 0
isAnagrambooleanFlag initialized true; flips to false on length or count mismatch
i, jintLoop indices for string characters (0–5) and alphabet slots (0–25)
c1, c2charCurrent uppercase characters from a and b; e.g., 'L' and 'S'
🎯 1-on-1 Live Mentorship & Free Study Kit

Nail Arrays & String Algorithms in BlueJ

Get 1-on-1 ICSE coaching on frequency arrays, character sorting, and tricky Section B string programs before your pre-boards.

💬 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: Checking only s2.indexOf(s1.charAt(i)) != -1, which wrongly classifies "hello" and "heloo" as anagrams.
  • Avoid Mistake: Indexing freq[c1 - 'A'] without normalizing case first, throwing ArrayIndexOutOfBoundsException on lowercase letters ('a' - 'A' = 32 >= 26).
  • Avoid Mistake: Comparing char[] arrays using arr1 == arr2 instead of Arrays.equals(arr1, arr2), which tests object references rather than contents.
  • Examiner / Mentor Tip: If your teacher prefers sorting, char[] a1 = a.toCharArray(); char[] a2 = b.toCharArray(); Arrays.sort(a1); Arrays.sort(a2); works cleanly since java.util.* already imports Arrays.
  • Examiner / Mentor Tip: Explicitly guard against non-alphabetic characters before indexing freq[c - 'A'] so digits or symbols cannot crash the array.
  • Examiner / Mentor Tip: Mentally test unequal-frequency pairs like "aabb" and "abbb" during revision to confirm your logic catches duplicate mismatches.

7. Interactive Concept Check Quiz

Question: Why does checking only s1.length() == s2.length() and s2.indexOf(s1.charAt(i)) != -1 fail as an anagram test?

8. Frequently Asked Questions

Should spaces be ignored when checking anagram strings in ICSE?
Many ICSE questions test single words like `"HEART"` and `"EARTH"`, while advanced ones test phrases like `"Dormitory"` and `"Dirty Room"`. Using `replace(" ", "")` handles both seamlessly. Unless the question explicitly states that spaces must be counted as characters, stripping spaces before length comparison is the safest choice.
Which is better for ICSE exams: Arrays.sort() or a 26-element frequency array?
Both score full marks when implemented properly. The 26-element `int[]` array demonstrates strong algorithmic control over ASCII offsets (`ch - 'A'`) without relying on `Arrays.sort()`, which examiners appreciate. However, `Arrays.sort()` is shorter and naturally supports digits and punctuation if your question includes alphanumeric strings.
What happens if a user enters digits or symbols in the frequency-array program?
Because the frequency array has indices `0` to `25` only for `'A'` through `'Z'`, passing a digit like `'2'` (`50 - 65 = -15`) would throw an `ArrayIndexOutOfBoundsException`. Our range guard `c1 >= 'A' && c1 <= 'Z'` safely catches non-letters and sets `isAnagram = false` instead of crashing.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class