Check Anagram Strings in Java — Definition, Examples and Program

Learn how to check whether two strings are anagrams in Java. This blog explains the concept, examples, and a clean Java program using character frequency logic.

Check Anagram Strings in Java

Two strings are called Anagrams if they contain the same characters with the same frequency but in a different order.

Anagram checking is a popular interview question and is commonly used in string analysis, search engines, and text processing.

Rules for Anagram Strings

How the Logic Works

  1. If the lengths of both strings are different, they are not anagrams.
  2. Create an integer array to store character frequencies.
  3. Increment count for characters of the first string.
  4. Decrement count for characters of the second string.
  5. If all values are zero, the strings are anagrams.

Example 1

String 1: "listen"

String 2: "silent"

Result: Strings are Anagrams

Example 2

String 1: "hello"

String 2: "world"

Result: Strings are Not Anagrams

Java Program to Check Anagram Strings


import java.util.Scanner;

public class AnagramCheck {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first string: ");
        String str1 = sc.nextLine();

        System.out.print("Enter second string: ");
        String str2 = sc.nextLine();

        // Remove spaces and convert to lowercase
        str1 = str1.replace(" ", "").toLowerCase();
        str2 = str2.replace(" ", "").toLowerCase();

        if (str1.length() != str2.length()) {
            System.out.println("Strings are Not Anagrams");
            return;
        }

        int[] freq = new int[256];

        for (int i = 0; i < str1.length(); i++) {
            freq[str1.charAt(i)]++;
            freq[str2.charAt(i)]--;
        }

        boolean isAnagram = true;

        for (int count : freq) {
            if (count != 0) {
                isAnagram = false;
                break;
            }
        }

        if (isAnagram) {
            System.out.println("Strings are Anagrams");
        } else {
            System.out.println("Strings are Not Anagrams");
        }
    }
}

Sample Output


Enter first string: listen
Enter second string: silent
Strings are Anagrams

Enter first string: java
Enter second string: avaJ
Strings are Anagrams

Important Notes

Practice Challenges

  1. Check anagrams without using an array.
  2. Check anagrams using sorting logic.
  3. Check anagrams for Unicode characters.

Anagram checking improves your understanding of character frequency and efficient string comparison techniques.