In this blog post, we’ll explore how to check if two strings are anagrams of each other in Java. This is a frequently asked question in Java interviews and string-related coding problems.
๐ What is an Anagram?
Two strings are anagrams if they contain the same characters in the same quantity but in any order.
๐ Examples
- "listen" and "silent" → ✅ Anagrams
- "hello" and "world" → ❌ Not Anagrams
✅ Java Program to Check Anagram (Using Sorting)
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
boolean result = areAnagrams(str1, str2);
System.out.println("Are they anagrams? " + result);
}
static boolean areAnagrams(String s1, String s2) {
if (s1.length() != s2.length())
return false;
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
}
✅ Output
Are they anagrams? true
๐ก Alternate Approach (Using Frequency Counting)
You can also use a HashMap or integer array (for lowercase English letters) to count character frequencies.
๐ง Interview Tip
This question tests your knowledge of string manipulation, sorting, and data structures. Be ready to explain both time complexity and space complexity of your approach.
๐ Conclusion
We’ve seen how to check if two strings are anagrams using sorting. This is a foundational string question often asked in technical interviews for Java developers.
๐งฎ Master Java String Comparison Problems
Checking whether two strings are anagrams is a classic Java interview and coding-round problem. Strengthen your understanding of string traversal, sorting, and frequency counting by exploring these closely related Java problems.
๐ง Java Coding Round Questions
Practice frequently asked string and comparison problems.
๐ฆ Java Collections Interview Questions
Learn how HashMap and arrays are used in string comparison logic.
๐งต Java String Pool & Interning
Understand string immutability and memory behavior in Java.
๐ First Non-Repeated Character
Another frequency-based string problem asked in interviews.
๐ Character Occurrence Count
Learn frequency counting — the foundation of anagram logic.
๐ Palindrome String Program
Practice string comparison using reverse and two-pointer logic.
๐ Reverse String in Java
Strengthen string traversal and manipulation techniques.
๐ข String Contains Only Digits
Practice validation-based string processing problems.
๐ฏ Java Interview Questions (Freshers)
Common interview questions involving strings and collections.
๐งช Advanced Java Programs (Real-World)
Apply string comparison logic in real-world Java scenarios.