Anagram Check Program in Java
In this lesson: Check if two strings are anagrams in Java using sorting and counting — code, dry run and output. In Hindi & English.
What is an anagram
Two words are anagrams if they use exactly the same letters, just in a different order — like listen and silent. Checking for anagrams in Java is a classic string exercise, and there are two neat ways: sorting and counting characters.
The sorting method
import java.util.Arrays; String a = "listen", b = "silent"; char[] x = a.toCharArray(); char[] y = b.toCharArray(); Arrays.sort(x); Arrays.sort(y); System.out.println(Arrays.equals(x, y));
We turn each string into a char array, sort both, and compare. If they are anagrams, sorting makes them identical — Arrays.equals then returns true.
Dry run
| Step | What | Value |
|---|---|---|
| 1 | chars of "listen" | l i s t e n |
| 2 | sorted | e i l n s t |
| 3 | chars of "silent" | s i l e n t |
| 4 | sorted | e i l n s t |
| 5 | compare sorted arrays | e i l n s t == e i l n s t → Anagram! |
Anagrams use the same letters, so once both are sorted they become identical. Comparing the sorted forms is a quick, reliable check.
The counting method
String a = "listen", b = "silent";
if (a.length() != b.length()) {
System.out.println("Not anagram");
} else {
int[] count = new int[26];
for (char c : a.toCharArray()) count[c - 'a']++;
for (char c : b.toCharArray()) count[c - 'a']--;
boolean anagram = true;
for (int n : count) if (n != 0) anagram = false;
System.out.println(anagram);
}
We add up letters from the first word and subtract those from the second. If every count ends at 0, both words used the same letters — they are anagrams. This avoids sorting.
Cleaning the input
For real checks, ignore case and spaces first:
a = a.toLowerCase().replaceAll("\\s", "");
b = b.toLowerCase().replaceAll("\\s", "");
This lets "Listen" and "Silent", or phrase anagrams like "conversation" and "voices rant on", compare correctly regardless of case and spacing.
Common mistakes
- Not checking lengths. Different lengths can never be anagrams — check first.
- Ignoring case and spaces. Lowercase and strip spaces for phrases.
- Comparing arrays with
==. UseArrays.equals, not==. - Assuming only lowercase letters in counting. The
c - 'a'trick assumes a-z only.
Summary
- Anagrams use the same letters in a different order.
- Sorting method: sort both char arrays and compare with
Arrays.equals. - Counting method: add letters from one, subtract from the other, check all zeros.
- Lowercase and remove spaces for phrase anagrams.
- Different lengths mean not anagrams.
Next, reverse text in reverse a string, or sort with bubble sort.
