Check if Two Strings are Anagrams in Java

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.