Anagram Program In Java


In this article, we will see how to write an anagram program in Java. We have discussed 4 different ways to check if two given strings are anagrams of each other or not.

    Table Of Contents

  1. What is an Anagram?
  2. Anagram Programs in Java
    1. Method 1: Sort the Strings
    2. Method 2: Count the Characters
    3. Method 3: Use HashMap
    4. Method 4: Remove Character From Second String
  3. Conclusion

What is Anagram?

A word, phrase, or name formed by rearranging the letters of another word, phrase, or name is called an anagram. For example, the word iceman is an anagram of the word cinema.

Another example could be "rail safety" to "fairy tales" or "Astronomer" to "moon starer".

Anagram in programming
Anagram in programming

Java Programs to Check Anagram

Here are 4 different anagram programs in Java to check if two given strings are anagrams of each other or not. Complete codes of all programs are given.

Method 1: Using Sorting

One of the simplest ways to check if two strings are anagrams of each other is to sort the characters of both the strings and then compare them. If both strings are anagrams, then both the strings will be equal after sorting.

For example:

"cinema" => sorted => "aceimn"
"iceman" => sorted => "aceimn"

"aceimn" == "aceimn"
So both the strings are anagrams of each other.

Here is the complete code of this method:

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

public class AnagramUsingSorting {
    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();
        sc.close();
        if (isAnagram(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagrams");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams");
        }
    }

    public static boolean isAnagram(String s1, String s2) {
      // remove spaces and convert to lowercase
      s1 = s1.replaceAll("\\s", "").toLowerCase();
      s2 = s2.replaceAll("\\s", "").toLowerCase();

      // check if length is same
      if (s1.length() != s2.length()) {
        return false;
      }
      // convert to char array and sort
      char[] c1 = s1.toCharArray();
      char[] c2 = s2.toCharArray();
      Arrays.sort(c1);
      Arrays.sort(c2);
      return Arrays.equals(c1, c2);
    }
}

Output:

Enter first string: cinema
Enter second string: iceman
cinema and iceman are anagrams

Method 2: Counting Each Character Using Array

In this method, we will create an array of size 26 to store the count of each character in both strings.

We will execute a loop from 0 to the length of the strings (both strings will be of the same length) and increment the count of the character at the ith index for str1 and decrement the count of the character at the ith index for str2.

This way if both the strings are anagrams, then the array will contain all zeros.

For example:

str1 = "peek"
str2 = "keep"

iteration 1:
    count['p'-'a'] = 0 + 1 = 1 (pcount = 1)
    count['k'-'a'] = 0 - 1 = -1 (kcount = -1)
iteration 2:
    count['e'-'a'] = 0 + 1 = 1 (ecount = 1)
    count['e'-'a'] = 1 - 1 = 0 (ecount = 0)
iteration 3:
    count['e'-'a'] = 0 + 1 = 1 (ecount = 1)
    count['e'-'a'] = 1 - 1 = 0 (ecount = 0)
iteration 4:
    count['k'-'a'] = -1 + 1 = 0 (kcount = 0)
    count['p'-'a'] = 1 - 1 = 0 (pcount = 0)

Final all the values in the array will be 0,
So both the strings are anagrams of each other.

Let's look at the Java program for this method:

import java.util.Scanner;

public class AnagramUsingArray {
    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();
        sc.close();
        if (isAnagram(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagrams");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams");
        }
    }

    public static boolean isAnagram(String s1, String s2) {
      // remove spaces and convert to lowercase
      s1 = s1.replaceAll("\\s", "").toLowerCase();
      s2 = s2.replaceAll("\\s", "").toLowerCase();

      // check if length is same
      if (s1.length() != s2.length()) {
        return false;
      }

      // create an array of size 26
      int[] count = new int[26];

      // increment count for str1 and decrement count for str2
      for (int i = 0; i < s1.length(); i++) {
        count[s1.charAt(i) - 'a']++;
        count[s2.charAt(i) - 'a']--;
      }

      // check if all the values in the array are 0
      for (int i = 0; i < 26; i++) {
        if (count[i] != 0) {
          return false;
        }
      }
      return true;
    }
}

Output:

Enter first string: keep
Enter second string: peek
keep and peek are anagrams

Method 3: Counting Each Character Using HashMap

In this method, we will create a HashMap to store the count of each character in both strings.

Create a HashMap and store the count of each character of str1 in it.

Then execute a loop from 0 to length of the string str2 and decrement the count of those characters from the HashMap.

If the count of any character becomes 0, then remove that character from the HashMap.

If a character is not present in the HashMap return false.

Finally, if the HashMap is empty, then both the strings are anagrams of each other.

Here is the Java program for this method:

import java.util.HashMap;
import java.util.Scanner;

public class AnagramUsingHashMap {
    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();
        sc.close();
        if (isAnagram(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagrams");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams");
        }
    }

    public static boolean isAnagram(String s1, String s2) {
      // remove spaces and convert to lowercase
      s1 = s1.replaceAll("\\s", "").toLowerCase();
      s2 = s2.replaceAll("\\s", "").toLowerCase();

      // check if length is same
      if (s1.length() != s2.length()) {
        return false;
      }

      // create a HashMap
      HashMap<Character, Integer> map = new HashMap<>();

      // store the count of each character of str1 in the HashMap
      for (int i = 0; i < s1.length(); i++) {
        char c = s1.charAt(i);
        if (map.containsKey(c)) {
          map.put(c, map.get(c) + 1);
        } else {
          map.put(c, 1);
        }
      }

      // decrement the count of each character of str2 from the HashMap
      for (int i = 0; i < s2.length(); i++) {
        char c = s2.charAt(i);
        if (map.containsKey(c)) {
          map.put(c, map.get(c) - 1);
          // if the count becomes 0
          // then remove that character from the HashMap
          if (map.get(c) == 0) {
            map.remove(c);
          }
        } else {
          return false;
        }
      }

      // if the HashMap is empty
      // then both the strings are anagrams of each other
      return map.isEmpty();
    }
}

Output:

Enter first string: Astronomer
Enter second string: Moon starer
Astronomer and Moon starer are anagrams

Method 4: Remove Character From Second String

Here is another approach to solve this problem. We will remove each character of str1 from str2 and check if the length of str2 is 0 or not.

If the length of str2 is 0, then both the strings are anagrams of each other.

Here is the Java program for this method:

import java.util.Scanner;

public class AnagramUsingRemove {
    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();
        sc.close();
        if (isAnagram(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagrams");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams");
        }
    }

    public static boolean isAnagram(String s1, String s2) {
      // remove spaces and convert to lowercase
      s1 = s1.replaceAll("\\s", "").toLowerCase();
      s2 = s2.replaceAll("\\s", "").toLowerCase();

      // check if length is same
      if (s1.length() != s2.length()) {
        return false;
      }

      // remove each character of str1 from str2
      for (int i = 0; i < s1.length(); i++) {
        char c = s1.charAt(i);
        int index = s2.indexOf(c);
        if (index != -1) {
          s2 = s2.substring(0, index) + s2.substring(index + 1, s2.length());
        } else {
          return false;
        }
      }

      // if the length of str2 is 0
      // then both the strings are anagrams of each other
      return s2.length() == 0;
    }
}

Output:

Enter first string: Astronomer
Enter second string: Moon starer
Astronomer and Moon starer are anagrams

Stay Ahead, Learn More


Conclusion

We have seen 4 different ways to tell if two strings are anagrams in Java. You can use any of these methods as per your requirement.

Reference: Wikipedia