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.