Java Tutorial
🔍
What is OOP?Classes & ObjectsConstructorsAccess Modifiersthis Keywordstatic KeywordEncapsulationInheritancesuper KeywordMethod OverridingOverloading vs OverridingPolymorphismUpcasting & Downcastinginstanceof OperatorAbstractionAbstract ClassesInterfacesMarker InterfacesAbstract Class vs InterfaceObject ClasstoString() Methodequals() & hashCode()
Collections OverviewCollections HierarchyIterable InterfaceCollection InterfaceMap Interfaceequals() and hashCode()IteratorListIteratorFail-fast vs Fail-safe IteratorConcurrentModificationExceptionArrayListLinkedListHashSetLinkedHashSetTreeSetQueuePriorityQueueDequeArrayDequeHashMapLinkedHashMapTreeMapConcurrentHashMapCopyOnWriteArrayListList vs Set vs MapChoosing the Right CollectionComparableComparatorComparable vs ComparatorCollections Utility ClassArrays Utility ClassImmutable CollectionsCollection vs CollectionsVectorHashtableStackArrayList Internal WorkingLinkedList Internal WorkingHashMap Internal WorkingTreeMap Internal Working
Check Anagram in Java
intermediate· Strings · String
Problem
Anagrams are words or strings that contain the same characters with the same frequencies, but possibly in a different order.
Given two strings, determine whether they are anagrams.
Input
"listen", "silent"
Output
Anagram: true
Java Program
Java
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String a = "listen", b = "silent";
char[] ca = a.toCharArray();
char[] cb = b.toCharArray();
// Sorting puts both arrays into the same canonical order
Arrays.sort(ca);
Arrays.sort(cb);
// Anagrams sort to identical character arrays
boolean isAnagram = Arrays.equals(ca, cb);
System.out.println("Anagram: " + isAnagram);
}
}Output
Anagram: true
Core Logic
Sort the letters of both strings and compare — if they match, one is just a shuffled version of the other.
How It Works
- 1Both strings are converted to
char[]arrays withtoCharArray(). - 2
Arrays.sort()puts each array's characters into the same canonical (alphabetical) order. - 3
Arrays.equals()compares the two sorted arrays element by element. - 4If the sorted arrays are identical, the original strings must contain exactly the same characters, just rearranged.
"listen" sorts to eilnst, and "silent" also sorts to eilnst — so they're reported as anagrams.💡
Key Point: Sorting both strings turns the comparison into a simple array-equality check — no manual character-frequency counting needed.
Key Concepts
Arrays.sort()Arrays.equals()char[]
Approach 2: Frequency Count Array
Java
public class AnagramCheckFrequency {
public static void main(String[] args) {
String a = "listen", b = "silent";
boolean isAnagram = true;
// Different lengths can never be anagrams
if (a.length() != b.length()) {
isAnagram = false;
} else {
int[] counts = new int[26]; // one slot per letter a-z
for (int i = 0; i < a.length(); i++) {
counts[a.charAt(i) - 'a']++; // increment for each letter in a
counts[b.charAt(i) - 'a']--; // decrement for each letter in b
}
// If every increment was canceled by a matching decrement, all slots are 0
for (int count : counts) {
if (count != 0) {
isAnagram = false;
break;
}
}
}
System.out.println("Anagram: " + isAnagram);
}
}
Output
Anagram: true
Core Logic
Sorting isn't the only option — tallying letter counts in a small array gets the same answer without touching either string's order.
How It Works
- 1A quick length check runs first — strings of different lengths can never be anagrams.
- 2A 26-element
int[]tracks the running difference in letter counts, one slot per letter of the alphabet. - 3
counts[a.charAt(i) - 'a']++increments the slot for each letter ina; the matching decrement forbhappens in the same loop pass. - 4If the strings are anagrams, every increment from
ais canceled out by a decrement fromb, leaving every slot at0. - 5A final pass checks that no slot ended up non-zero.
For
"listen" and "silent", every letter appears the same number of times in both, so every slot in counts ends at 0.💡
Key Point: This runs in O(n) time, faster than the O(n log n) sorting approach — the trade-off is that it only works cleanly for a known, fixed character set like lowercase letters.
Key Concepts
frequency countchar arithmeticarray