0
0
JavaProgramBeginner · 2 min read

Java Program to Check Anagram with Example

You can check if two strings are anagrams in Java by sorting their characters and comparing them using Arrays.sort() and Arrays.equals(), like this: Arrays.sort(charArray1); Arrays.sort(charArray2); return Arrays.equals(charArray1, charArray2);.
📋

Examples

Inputlisten, silent
OutputThe strings are anagrams.
Inputhello, world
OutputThe strings are not anagrams.
Inputevil, live
OutputThe strings are anagrams.
🧠

How to Think About It

To check if two words are anagrams, think about whether they have the same letters in the same amounts. If you sort the letters of both words, they should look exactly the same if they are anagrams. So, convert both words to character arrays, sort them, and then compare.
📐

Algorithm

1
Get two input strings.
2
Remove spaces and convert both strings to lowercase.
3
Convert both strings to character arrays.
4
Sort both character arrays.
5
Compare the sorted arrays; if they are equal, the strings are anagrams.
6
Return the result.
💻

Code

java
import java.util.Arrays;

public class AnagramCheck {
    public static boolean areAnagrams(String s1, String s2) {
        s1 = s1.replaceAll("\\s", "").toLowerCase();
        s2 = s2.replaceAll("\\s", "").toLowerCase();
        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);
    }

    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";
        if (areAnagrams(str1, str2)) {
            System.out.println("The strings are anagrams.");
        } else {
            System.out.println("The strings are not anagrams.");
        }
    }
}
Output
The strings are anagrams.
🔍

Dry Run

Let's trace the example strings "listen" and "silent" through the code.

1

Input strings

s1 = "listen", s2 = "silent"

2

Remove spaces and lowercase

s1 = "listen", s2 = "silent" (no spaces, already lowercase)

3

Check length

Both lengths are 6, continue

4

Convert to char arrays

arr1 = ['l','i','s','t','e','n'], arr2 = ['s','i','l','e','n','t']

5

Sort arrays

arr1 = ['e','i','l','n','s','t'], arr2 = ['e','i','l','n','s','t']

6

Compare arrays

Arrays are equal, return true

Steparr1arr2Equal?
Before sort['l','i','s','t','e','n']['s','i','l','e','n','t']No
After sort['e','i','l','n','s','t']['e','i','l','n','s','t']Yes
💡

Why This Works

Step 1: Normalize strings

Removing spaces and converting to lowercase ensures the comparison ignores case and spaces.

Step 2: Sort characters

Sorting the characters puts letters in order, so anagrams will have identical sorted arrays.

Step 3: Compare sorted arrays

If the sorted arrays match exactly, the strings are anagrams; otherwise, they are not.

🔄

Alternative Approaches

Character count using frequency arrays
java
public static boolean areAnagramsCount(String s1, String s2) {
    s1 = s1.replaceAll("\\s", "").toLowerCase();
    s2 = s2.replaceAll("\\s", "").toLowerCase();
    if (s1.length() != s2.length()) return false;
    int[] count = new int[26];
    for (int i = 0; i < s1.length(); i++) {
        count[s1.charAt(i) - 'a']++;
        count[s2.charAt(i) - 'a']--;
    }
    for (int c : count) {
        if (c != 0) return false;
    }
    return true;
}
This method uses counting and is faster for large strings but only works for alphabets.
Using HashMap to count characters
java
import java.util.HashMap;

public static boolean areAnagramsMap(String s1, String s2) {
    s1 = s1.replaceAll("\\s", "").toLowerCase();
    s2 = s2.replaceAll("\\s", "").toLowerCase();
    if (s1.length() != s2.length()) return false;
    HashMap<Character, Integer> map = new HashMap<>();
    for (char c : s1.toCharArray()) {
        map.put(c, map.getOrDefault(c, 0) + 1);
    }
    for (char c : s2.toCharArray()) {
        if (!map.containsKey(c)) return false;
        map.put(c, map.get(c) - 1);
        if (map.get(c) < 0) return false;
    }
    return true;
}
This method works for any characters but uses more memory and is slower than sorting for small strings.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting both strings takes O(n log n) time where n is the length of the strings, which dominates the runtime.

Space Complexity

Extra space is used for character arrays and sorting, which is O(n).

Which Approach is Fastest?

Counting characters with arrays is O(n) and faster for alphabets, but sorting is simpler and works for all characters.

ApproachTimeSpaceBest For
Sorting and comparingO(n log n)O(n)General use, any characters
Counting with frequency arrayO(n)O(1)Only alphabets, very fast
HashMap countingO(n)O(n)Any characters, including unicode
💡
Always convert strings to lowercase and remove spaces before checking for anagrams to avoid false mismatches.
⚠️
Beginners often forget to normalize case or remove spaces, causing correct anagrams to be marked as not anagrams.