ISC Practicals and Theory - Anagram
Updated 21 Oct 2026
Two words or phrases are anagrams if one can be made by rearranging the letters of the other. This program, written in the main method alone, reads two lines, counts how many times each letter occurs in each of them using two int arrays of size 26, and compares the two arrays position by position.
Definition
Two strings are anagrams if they contain exactly the same letters with exactly the same frequencies. This program ignores case, spaces and every character that is not a letter.
ListenandSilentare anagrams: both have e, i, l, n, s, t once each.DormitoryandDirty roomare anagrams: d, i, m, t, y once, o and r twice in both. The space is ignored.HelloandHeloare not:loccurs twice in the first and once in the second.- Identical strings such as
HelloandHelloare anagrams of each other, since the letters and counts are the same. - A line with no letters at all (for example
123or?!) has nothing to rearrange, so such a pair givesNOT ANAGRAMS.
Algorithm
- Read the two lines into
aandb. If either is empty, printINVALID INPUTand stop. - Create two arrays
faandfbof size 26, all 0.fa[0]counts the letter a ina,fa[1]counts b, and so on up tofa[25]for z. - Visit every character
chofa. If it is a capital letter, add 32 to bring it to the small-letter range. If it is now between'a'and'z', add 1 tofa[ch - 'a']. Spaces, digits and punctuation marks are ignored. NoCharacter.isLetter()ortoLowerCase()is used, only character arithmetic. - Do the same for
bandfb. - For every index
ifrom 0 to 25, note whetherfa[i]orfb[i]is above 0 (hasA,hasB), and setsame = falseiffa[i] != fb[i]. One different count is enough to fail. - If both lines have at least one letter and
sameis still true, printANAGRAMS. Otherwise printNOT ANAGRAMS.
Program
The two for loops in main fill the frequency tables, and a third loop compares them.
import java.util.Scanner;
/* Program Anagram checks whether two words or phrases are anagrams: they
use exactly the same letters with the same frequencies. Case, spaces and
all non-letters are ignored. */
public class Anagram
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first word or phrase: ");
String a = sc.nextLine(); // the first word or phrase
System.out.print("Enter the second word or phrase: ");
String b = sc.nextLine(); // the second word or phrase
if (a.length() == 0 || b.length() == 0)
{
System.out.println("INVALID INPUT");
return;
}
int fa[] = new int[26]; // fa[0] counts 'a' in a, fa[1] counts 'b' ... fa[25] counts 'z'
int fb[] = new int[26]; // same frequency table for the second string b
int i;
char ch;
for (i = 0; i < a.length(); i++) // visit every character of a
{
ch = a.charAt(i);
if (ch >= 'A' && ch <= 'Z') // capital letter: bring it to the small-letter range
ch = (char) (ch + 32);
if (ch >= 'a' && ch <= 'z') // spaces, digits and punctuation are ignored
fa[ch - 'a']++; // 'a' -> 0 ... 'z' -> 25
}
for (i = 0; i < b.length(); i++) // visit every character of b
{
ch = b.charAt(i);
if (ch >= 'A' && ch <= 'Z')
ch = (char) (ch + 32);
if (ch >= 'a' && ch <= 'z')
fb[ch - 'a']++;
}
boolean hasA = false, hasB = false; // does a (or b) contain at least one letter?
boolean same = true; // stays true while all counts are equal
for (i = 0; i < 26; i++)
{
if (fa[i] > 0)
hasA = true;
if (fb[i] > 0)
hasB = true;
if (fa[i] != fb[i]) // one different count is enough to fail
same = false;
}
if (hasA && hasB && same) // a line without letters has nothing to rearrange
System.out.println("ANAGRAMS");
else
System.out.println("NOT ANAGRAMS");
}
}Variable description table
| Variable | Data Type | Purpose |
|---|---|---|
args | String[] | Command line arguments of main; not used |
sc | Scanner | Reads the input typed by the user |
a | String | The first word or phrase |
b | String | The second word or phrase |
fa | int[] | Frequency table of a: fa[0] counts a, ... fa[25] counts z |
fb | int[] | Frequency table of b |
i | int | Loop counter over the characters or over the 26 table positions |
ch | char | The character being examined, changed to a small letter if it is a capital |
hasA | boolean | True if a contains at least one letter |
hasB | boolean | True if b contains at least one letter |
same | boolean | Stays true while all 26 counts of the two tables are equal |
Sample input and output
Sample 1
Enter the first word or phrase: Listen
Enter the second word or phrase: Silent
ANAGRAMSSample 2
Enter the first word or phrase: Dormitory
Enter the second word or phrase: Dirty room
ANAGRAMSSample 3
Enter the first word or phrase: Hello
Enter the second word or phrase: Helo
NOT ANAGRAMSSample 4
Enter the first word or phrase: Hello
Enter the second word or phrase: Hello
ANAGRAMSSample 5
Enter the first word or phrase: 123
Enter the second word or phrase: ?!
NOT ANAGRAMSDry run
Input Hello and Helo. The counting loops fill the tables below (letters not listed have count 0).
| Letter | h | e | l | o |
|---|---|---|---|---|
| Index | 7 | 4 | 11 | 14 |
fa[] for Hello | 1 | 1 | 2 | 1 |
fb[] for Helo | 1 | 1 | 1 | 1 |
The last loop compares from index 0. Indices 0 to 3 are 0 and 0, index 4 (e) is 1 and 1, indices 5 and 6 are equal, index 7 (h) is 1 and 1, and indices 8 to 10 are equal. At index 11 (l), fa[11] is 2 and fb[11] is 1, which differ, so same becomes false and the program prints NOT ANAGRAMS. This is the same as the real run above.
Variations
- Pangram "Write a program to check whether a sentence contains every letter of the alphabet."
- Letter frequency "Write a program to accept a sentence and print the frequency of each letter in it."
- Isogram "Write a program to check whether a word has no repeated letter."