Summarise With AI
Back

Anagram Program in Java: A Comprehensive Guide with Code Examples

30 Jan 2026
5 min read

What This Blog Covers

  • Explores multiple ways to implement an Anagram Program in Java, from simple logic to optimized solutions.
  • Demonstrates five different techniques: sorting, character counting, ASCII frequency arrays, streams, and recursion.
  • Explains performance trade-offs so it’s clear why some approaches are faster and more scalable than others.
  • Covers real input challenges, including spaces, case sensitivity, and dynamic user input.
  • Helps identify the most suitable anagram-checking method based on problem constraints and interview expectations.

Introduction

Anagram Program in Java is more than just a word puzzle; it’s a problem that tests how well you understand strings, character manipulation, and algorithmic efficiency. Two strings may look completely different, yet still be anagrams if they contain the same characters arranged differently.

In real-world programming and interviews, checking for anagrams goes beyond simple comparison. Developers must consider performance, input size, character encoding, and edge cases like spaces, case sensitivity, and punctuation. A solution that works for small words may fail when handling large datasets or Unicode text.

This guide walks through multiple ways to build an Anagram Program in Java, from beginner-friendly sorting techniques to optimized character frequency methods. You’ll learn how each approach works, when to use it, and how to choose the most efficient solution based on real constraints.

Definition of Anagram

An anagram is a word, phrase, or name formed by rearranging the letters of another. The core rule is that both the original and the transformed word must use the exact same letters in the same frequency, just in a different order.

Key Characteristics of Anagrams:

  1. Same Letters, Different Order: An anagram must contain all the original letters, but in a new arrangement.
  2. Letter Frequency Matters: If one word has more of a certain letter than the other, it is not a valid anagram.
  3. Spaces and Punctuation Are Ignored: Most anagram rules disregard spaces, hyphens, apostrophes, and other symbols.
  4. Case Sensitivity: Typically, anagrams ignore uppercase and lowercase distinctions unless explicitly required.
  5. Meaning Can Vary: Some anagrams create meaningful words or phrases, while others may just be random letter rearrangements.

Examples of Anagrams:

  • "Debit card" and "Bad credit"
  • "Astronomer" and "Moon starer"
  • "School master" and "The classroom"

Why check for Anagrams?

Anagram detection has practical applications in various fields, including entertainment, security, and computational linguistics. Here’s why it matters:

1. Word Games & Puzzles

  • Many games, like Scrabble, Boggle, and crosswords, involve finding or rearranging letters into meaningful words.
  • Trivia and brain-training apps often use anagrams as a mental exercise to improve vocabulary and cognitive skills.
  • Online anagram solvers help players generate valid words from jumbled letters.

2. Cryptography & Steganography

  • Historical Encryption – In earlier times, anagrams were used to disguise secret messages.
  • Hidden Meanings – Some ciphers involve rearranging words to conceal or reveal information.
  • Modern Security – Certain cryptographic algorithms use anagram-like permutations to strengthen encryption and hashing methods.

3. Natural Language Processing (NLP)

  • Text Analysis & Data Cleaning: Anagram program in Java detection helps process and analyze text, such as recognizing variations of the same word.
  • Plagiarism & Similarity Detection: Some plagiarism detection tools check for reworded content that might include anagrams or rearranged phrases.
  • Search Engine Optimization (SEO): Identifying anagram variations of keywords can improve search engine rankings.

4. Artificial Intelligence & Machine Learning

  • Pattern Recognition: AI models trained on text often detect anagrams to improve word relationships in applications like chatbots and translation tools.
  • Speech-to-Text Applications:  Voice recognition systems use anagram detection to resolve ambiguities in spoken language.

Methods to Check for Anagrams in Java

We will cover multiple approaches:

  1. Sorting Method
  2. Character Count Method
  3. Using the ASCII Character Frequency Array
  4. Using Streams and Lambda Expressions
  5. Recursive Method

Each method has its advantages and drawbacks. Let’s explore them in detail.

1. Sorting Method for Anagram Detection

In an Anagram program in Java, one common approach is to sort both strings and compare them. If their sorted forms are identical, it confirms that the strings are anagrams of each other.

Java Implementation

Below is the Anagram program in Java implemented using the sorting method.

This approach checks if two strings are anagrams by comparing their sorted character sequences.

import java.util.Arrays;

public class AnagramChecker {
    public static boolean areAnagrams(String str1, String str2) {
        // Remove spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        // If lengths don't match, they can't be anagrams
        if (str1.length() != str2.length()) return false;

        // Convert to character arrays
        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();

        // Sort both arrays
        Arrays.sort(charArray1);
        Arrays.sort(charArray2);

        // Compare sorted arrays
        return Arrays.equals(charArray1, charArray2);
    }

    public static void main(String[] args) {
        System.out.println(areAnagrams("Listen", "Silent"));  // Output: true
        System.out.println(areAnagrams("Hello", "World"));    // Output: false
        System.out.println(areAnagrams("Debit card", "Bad credit")); // Output: true
    }
}

Explanation

  1. Convert both strings to lowercase to ensure case insensitivity.
  2. Remove spaces and special characters (optional, depending on requirements).
  3. Convert the strings into character arrays.
  4. Sort both character arrays alphabetically.
  5. Compare the sorted arrays. If they are identical, the strings are anagrams.

Output:

true
false
true

Time Complexity Analysis

  • Sorting Step: The primary cost in this method comes from sorting both character arrays. The sorting operation takes O(n log n) time complexity (where n is the length of the string).
  • Comparison Step: The Arrays.equals() method runs in O(n) time.
  • Overall Complexity: Since sorting dominates, the final time complexity is O(n log n).

2. Character Count Method for Anagram Detection

The character count method checks if two strings are anagrams by counting the occurrences of each character in both strings. If the frequency distributions match, the strings are anagrams.

Java Implementation

Here's how you use the Character Count method to construct the Anagram program in Java. This method determines whether two strings are anagrams by comparing the frequency of each character in the two strings.

public class AnagramChecker {
    public static boolean areAnagrams(String str1, String str2) {
        // Remove spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        // If lengths don't match, they can't be anagrams
        if (str1.length() != str2.length()) return false;

        // Create a frequency array for ASCII characters (assuming 256 possible characters)
        int[] charCounts = new int[256];

        // Count frequency in first string
        for (char c : str1.toCharArray()) {
            charCounts[c]++;
        }

        // Decrease frequency in second string
        for (char c : str2.toCharArray()) {
            charCounts[c]--;
        }

        // If all values are zero, the strings are anagrams
        for (int count : charCounts) {
            if (count != 0) return false;
        }

        return true;
    }

    public static void main(String[] args) {
        System.out.println(areAnagrams("Listen", "Silent"));  // Output: true
        System.out.println(areAnagrams("Hello", "World"));    // Output: false
        System.out.println(areAnagrams("Debit card", "Bad credit")); // Output: true
    }
}

Explanation

  1. Convert both strings to lowercase to ensure case insensitivity.
  2. Remove spaces (optional, depending on requirements).
  3. Create a frequency array of size 256 (for ASCII characters) to store character counts.
  4. Iterate through the first string and increase the frequency count for each character.
  5. Iterate through the second string and decrease the frequency count for each character.
  6. If all values in the frequency array are zero, the strings are anagrams.

Output:

true
false
true

Time Complexity Analysis

  • Character Counting Step: Each string is scanned once → O(n)
  • Comparison Step: Checking the frequency array takes O(256) ≈ O(1) (constant time).
  • Overall Complexity: O(n) (significantly faster than the sorting method).

3. Using ASCII Character Frequency Array for Anagram Detection

This method determines whether two strings are Anagram program in Java by tracking the frequency of ASCII characters using a fixed-size integer array. Instead of sorting, we increment counts for one string and decrement for the other. If all values in the array are zero at the end, the strings are anagrams.

Java Implementation

Using the ASCII character frequency array approach, the Anagram program in Java is implemented below. This method effectively checks for anagrams by counting character occurrences.

public class AnagramChecker {
    public static boolean areAnagrams(String str1, String str2) {
        // Remove spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        // If lengths don't match, they can't be anagrams
        if (str1.length() != str2.length()) return false;

        // ASCII character frequency array (size 256)
        int[] charCounts = new int[256];

        // Process both strings simultaneously
        for (int i = 0; i < str1.length(); i++) {
            charCounts[str1.charAt(i)]++;  // Increment for str1
            charCounts[str2.charAt(i)]--;  // Decrement for str2
        }

        // Check if all counts are zero
        for (int count : charCounts) {
            if (count != 0) return false;
        }

        return true;
    }

    public static void main(String[] args) {
        System.out.println(areAnagrams("Listen", "Silent"));  // Output: true
        System.out.println(areAnagrams("Hello", "World"));    // Output: false
        System.out.println(areAnagrams("Debit card", "Bad credit")); // Output: true
    }
}

Explanation

  1. Convert both strings to lowercase to ensure case insensitivity.
  2. Remove spaces (optional, depending on requirements).
  3. Initialize an integer array of size 256 (to cover all ASCII characters).
  4. Iterate through the first string and increment the count for each character.
  5. Iterate through the second string and decrement the count for each character.
    If all values in the frequency array are zero, the strings are anagrams.

Output:

true
false
true

Time Complexity Analysis

  • Processing Step: Each string is traversed once → O(n)
  • Checking Step: The frequency array has a fixed size of 256 → O(1)
  • Overall Complexity: O(n) (fastest approach for ASCII strings).

4. Using Streams and Lambda Expressions for Anagram Detection

This method leverages the Java Streams API and lambda expressions to check if two strings are anagrams. It creates a frequency map of characters using functional programming constructs, reducing boilerplate code while maintaining efficiency.

Java Implementation

Here, an Anagram program in Java is implemented, using Streams and Lambda Expressions to provide a clear and effective solution. To compare the input strings' sorted character sequences, it makes advantage of contemporary Java features.

import java.util.function.Function;
import java.util.stream.Collectors;

public class AnagramChecker {
    public static boolean areAnagrams(String str1, String str2) {
        // Remove spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        // Compare character frequency maps
        return str1.chars().boxed()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .equals(
                str2.chars().boxed()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            );
    }

    public static void main(String[] args) {
        System.out.println(areAnagrams("Fried", "Fired"));       // Output: true
        System.out.println(areAnagrams("Listen", "Silent"));     // Output: true
        System.out.println(areAnagrams("Hello", "World"));       // Output: false
        System.out.println(areAnagrams("Debit card", "Bad credit")); // Output: true
    }
}

Explanation

  1. Convert both strings to lowercase and remove spaces.
  2. Convert each string into a stream of characters using .chars().
  3. Group characters and count their occurrences using Collectors.groupingBy().
  4. Compare the two frequency maps. If they are equal, the strings are anagrams.

Output:

true
true
false
true

Time Complexity Analysis

  • Character Processing Step: Each string is traversed once → O(n)
  • Grouping Step: Creating the frequency map is O(n)
  • Comparison Step: Two hash maps are compared in O(n)
  • Overall Complexity: O(n) (efficient for large strings).

5. Recursive Method for Anagram Detection

This method checks if two strings are anagrams by recursively removing matching characters from both strings until they are empty. If all characters match and are removed successfully, the strings are anagrams.

Java Implementation

Here is an example of a recursive Anagram program in Java. This method iteratively compares and eliminates matching characters to determine whether two strings are anagrams.

public class AnagramChecker {
    public static boolean areAnagrams(String str1, String str2) {
        // Remove spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        // Base cases
        if (str1.length() != str2.length()) return false;
        if (str1.isEmpty() && str2.isEmpty()) return true;

        // Take the first character of str1 and find it in str2
        char ch = str1.charAt(0);
        int index = str2.indexOf(ch);

        // If the character is not found in str2, it's not an anagram
        if (index == -1) return false;

        // Remove the character from str1 and str2, and recurse
        return areAnagrams(str1.substring(1), str2.substring(0, index) + str2.substring(index + 1));
    }

    public static void main(String[] args) {
        System.out.println(areAnagrams("abc", "cab"));         // Output: true
        System.out.println(areAnagrams("listen", "silent"));   // Output: true
        System.out.println(areAnagrams("hello", "world"));     // Output: false
        System.out.println(areAnagrams("debit card", "bad credit")); // Output: true
    }
}

Explanation

Base Case:

  • If both strings are empty, return true (they are anagrams).
  • If lengths differ, return false (they can't be anagrams).

Recursive Case:

  • Take the first character of str1.
  • Find its first occurrence in str2.
  • If found, remove it from str2 and recursively check the remaining characters.
  • If not found, return false.

Output:

true
true
false
true

Time Complexity Analysis

  • In each recursive call, the function removes a character, reducing the string length by 1.
  • Since finding the index of a character in str2 takes O(n) in the worst case, the total time complexity is O(n²).

Summary

  • The sorting method compares sorted character sequences and is easy to implement but slower for large strings.
  • Character Count Method checks letter frequency and offers the best performance for most cases.
  • ASCII Frequency Array is highly efficient for standard English text with constant extra space.
  • Streams & Lambda Approach provides clean, modern Java syntax with readable frequency mapping.
  • The recursive method demonstrates logical string reduction but is less efficient and mainly educational.

Alternative Implementations: Anagram Program Variations in Java

While the sorting method is a popular approach for checking anagrams, Java offers several alternative implementations that may be more efficient or suitable depending on your requirements. These variations can help you avoid the overhead of sorting, handle large datasets, or work with a broader range of character sets. Below are some widely used alternative approaches:

1. Character Frequency Array (Without Sorting)

Instead of sorting both strings, you can use a fixed-size array (typically of length 256 for extended ASCII) to count the frequency of each character. This method is particularly efficient for large strings or when you need to perform many comparisons, as it has a linear time complexity O(n).

How it works:

  • Remove spaces and convert both strings to lowercase.
  • If their lengths differ, return false.
  • Increment the frequency count for each character in the first string.
  • Decrement the frequency count for each character in the second string.
  • If all counts are zero at the end, the strings are anagrams.

Example Implementation:

public static boolean areAnagrams(String str1, String str2) {
    str1 = str1.replaceAll("\\s", "").toLowerCase();
    str2 = str2.replaceAll("\\s", "").toLowerCase();

    if (str1.length() != str2.length())
        return false;

    int[] charCounts = new int[256];

    for (char c : str1.toCharArray()) {
        charCounts[c]++;
    }

    for (char c : str2.toCharArray()) {
        charCounts[c]--;
    }

    for (int count : charCounts) {
        if (count != 0)
            return false;
    }

    return true;
}

Advantages:

  • Linear time complexity O(n).
  • No sorting overhead.
  • Simple and effective for ASCII-based strings.

2. Using HashMap for Unicode and Large Character Sets

For strings containing Unicode characters or non-English alphabets, a HashMap is a better choice than a fixed-size array. This approach allows for flexible and accurate frequency counting regardless of character set.

How it works:

  • Remove spaces and convert both strings to lowercase.
  • If their lengths differ, return false.
  • Use a HashMap to count the frequency of each character in the first string.
  • Decrease the frequency for each character in the second string.
  • If any frequency becomes negative or a character doesn't exist in the map, return false.

Example Implementation:

import java.util.HashMap;
import java.util.Map;

public static boolean areAnagrams(String str1, String str2) {
    str1 = str1.replaceAll("\\s", "").toLowerCase();
    str2 = str2.replaceAll("\\s", "").toLowerCase();

    if (str1.length() != str2.length())
        return false;

    Map<Character, Integer> charCountMap = new HashMap<>();

    for (char c : str1.toCharArray()) {
        charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
    }

    for (char c : str2.toCharArray()) {
        if (!charCountMap.containsKey(c) || charCountMap.get(c) == 0) {
            return false;
        }
        charCountMap.put(c, charCountMap.get(c) - 1);
    }

    return true;
}

Advantages:

  • Works with all Unicode characters.
  • Suitable for internationalization and multilingual applications.

3. Optimized Approaches for Large-Scale Comparisons

When you need to compare a large number of string pairs (for example, in a database or large collection), consider these optimizations:

  • Preprocessing: Normalize all strings (e.g., sort or frequency-map them) once and store the result. This allows fast comparison via hash codes or direct map comparison.
  • Hashing: Store normalized representations in a HashSet or HashMap for quick lookups and duplicate detection.

Benefits:

  • Reduces repeated computation.
  • Enables efficient batch processing.

4. Using Java Streams and Utility Methods

Modern Java features like Streams and Collectors can make your code more concise and expressive, especially for frequency counting.

Example with Streams:

import java.util.function.Function;
import java.util.stream.Collectors;

public static boolean areAnagrams(String str1, String str2) {
    str1 = str1.replaceAll("\\s", "").toLowerCase();
    str2 = str2.replaceAll("\\s", "").toLowerCase();

    return str1.chars()
               .boxed()
               .collect(Collectors.groupingBy(
                   Function.identity(),
                   Collectors.counting()
               ))
               .equals(
                   str2.chars()
                       .boxed()
                       .collect(Collectors.groupingBy(
                           Function.identity(),
                           Collectors.counting()
                       ))
               );
}

Advantages:

  • Concise and readable code.
  • Leverages Java’s functional programming capabilities.

When to Use Each Approach

  • Character Frequency Array: Best for ASCII strings and maximum speed.
  • HashMap: Best for Unicode or internationalized text.
  • Streams: For concise code and when using Java 8+ features.
  • Preprocessing & Hashing: When working with large datasets or needing to perform many repeated anagram checks.

Handling User Input for Anagram Checking in Java

In practical applications, it's important for your anagram program to accept input directly from users rather than relying solely on hardcoded strings. Handling user input allows users to check any pair of strings for anagram status interactively. In Java, this is typically achieved using the Scanner class.

Why Use User Input?

  • Flexibility: Users can test any pair of strings without modifying the code.
  • Real-World Scenarios: Most applications require dynamic input, not just preset examples.
  • Learning Opportunity: Understanding input handling is fundamental for beginner Java programmers.

How to Accept and Clean User Input

When accepting input, it's essential to:

  1. Prompt the user for two strings.
  2. Read the input using Scanner.
  3. Clean the input by converting it to lowercase and removing spaces, ensuring accurate anagram checking regardless of input formatting.

Example: Anagram Program with User Input

Below is a sample implementation that demonstrates how to handle user input and check if the provided strings are anagrams. This example uses the areAnagrams method defined earlier in this guide.

import java.util.Scanner;
import java.util.Arrays;

public class AnagramInputExample {

    public static boolean areAnagrams(String str1, String str2) {
        // Remove spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        // If lengths don't match, they can't be anagrams
        if (str1.length() != str2.length())
            return false;

        // Convert to character arrays and sort
        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();

        Arrays.sort(charArray1);
        Arrays.sort(charArray2);

        // Compare sorted arrays
        return Arrays.equals(charArray1, charArray2);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt user for input
        System.out.print("Enter the first string: ");
        String input1 = scanner.nextLine();

        System.out.print("Enter the second string: ");
        String input2 = scanner.nextLine();

        // Check if the input strings are anagrams
        if (areAnagrams(input1, input2)) {
            System.out.println(
                "\"" + input1 + "\" and \"" + input2 + "\" are anagrams."
            );
        } else {
            System.out.println(
                "\"" + input1 + "\" and \"" + input2 + "\" are not anagrams."
            );
        }

        // Close the scanner to avoid resource leaks
        scanner.close();
    }
}

How it works:

  • The program prompts the user to enter two strings.
  • Both strings are cleaned (spaces removed, converted to lowercase).
  • The areAnagrams method checks if they are anagrams using the sorting method.
  • The result is printed to the console.

Best Practices for User Input Handling

  • Always clean and normalize user input (remove spaces, convert to lowercase) before processing.
  • Prompt users clearly so they know what to enter.
  • Close the Scanner after use to release system resources.

Conclusion

Anagram detection is a fundamental string-processing problem that highlights the importance of choosing the right algorithm. While sorting-based solutions are easy to understand, optimized character-count techniques offer better performance for large inputs. Advanced approaches using streams, hash maps, and recursion provide flexibility for different use cases. Mastering the Anagram Program in Java not only prepares you for interviews but also strengthens your understanding of string handling, data structures, and algorithm optimization.

Key Takeaways

  1. Anagrams depend on character frequency, not word order or meaning.
  2. Sorting is simple but not optimal for large strings.
  3. Character frequency counting gives the best performance in most cases.
  4. Different character sets require different approaches (ASCII vs Unicode).
  5. Input normalization (spaces, case, symbols) is critical for accurate results.

Frequently Asked Questions

Below are some of the most common questions and clarifications related to anagram detection in Java:

1. What is an anagram in Java programming?

An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. In Java programming, checking for anagrams involves verifying that two strings have the same characters in the same frequency, regardless of order, spaces, or case.

2. What is the best way to check if two strings are anagrams in Java?

The most efficient way is to use a character frequency count (such as an ASCII array or a HashMap), which provides a time complexity of O(n). Sorting both strings and comparing them is another common method, but it is less efficient for long strings.

3. Why do we remove spaces and convert to lowercase when checking anagrams?

Spaces and case differences do not affect whether two strings are anagrams. Removing spaces and converting to lowercase ensures the comparison is accurate and case-insensitive.

4. Can anagram checking be applied to sentences or phrases?

Yes, anagram checking can be applied to multi-word phrases. Just make sure to remove spaces and punctuation before comparing.

5. Is recursion a good approach for checking anagrams?

While recursion can be used, it is less efficient (O(n²)) compared to iterative approaches like character counting or sorting. Recursion is mostly useful for educational purposes or when working with very short strings.

6. What is a pangram, and how is it different from an anagram?

A pangram is a sentence that contains every letter of the alphabet at least once (e.g., "The quick brown fox jumps over the lazy dog"). An anagram, on the other hand, is about rearranging letters to form another word or phrase. They are distinct concepts.

7. Can Java Streams be used for anagram detection?

Yes, Java Streams and lambda expressions can be used to create character frequency maps and compare them. This approach is concise and leverages modern Java features.

8. What are some real-world applications of anagram detection?

Anagram detection is used in word games, cryptography, natural language processing, plagiarism detection, and search engine optimization.

Summarise With Ai
ChatGPT
Perplexity
Claude
Gemini
Gork
ChatGPT
Perplexity
Claude
Gemini
Gork
Chat with us
Chat with us
Talk to career expert