How to Check if Two Words are Anagrams in Java

Permutations of a word are generated by shuffling the letters in the word. The full set consists of all permutations of the letters in a word. However only a subset of these are valid words in English language. These valid word combinations of letters is known as the Anagram for the original word and vice versa.

To verify whether two words are anagrams of each other we need to check whether they are the permutations of the same letter set and also whether they are valid words. However checking the second part is complex and requires access to the entire English dictionary. The following Java program only verifies that the given strings are permutations of the same set of letters.

Given two words for comparison, we first remove all the spaces and then convert the strings to lowercase for case insensitive comparison. We then convert each string to a character array and then sort it alphabetically. If the sorted character arrays are same we know that the words are anagrams of each other.

Java Program to Check Whether Two Words are Anagrams of Each Other

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

// Checks whether two words are anagrams of each other in Java
public class AnagramChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Please enter the first word: ");
        String word1 = scanner.nextLine();
        
        System.out.print("Please enter the second word: ");
        String word2 = scanner.nextLine();
        
        if(isAnagram(word1,word2)) {
            System.out.println(word1+" is an anagram of "+word2);
        }else {
            System.out.println(word1+" is NOT an anagram of "+word2);
        }

        scanner.close();
    }

    // Check if two words are anagrams in Java
    // Uses sorting and comparison of character arrays
    private static boolean isAnagram(String word1, String word2) {
       word1 = word1.replaceAll("\\s", "").toLowerCase();
       word2 = word2.replaceAll("\\s", "").toLowerCase();
       
       char[] word1Arr = word1.toCharArray();
       char[] word2Arr = word2.toCharArray();
       
       Arrays.sort(word1Arr);
       Arrays.sort(word2Arr);
       
       return (Arrays.equals(word1Arr, word2Arr));
    }
}

Following is a sample run of the above program,

java AnagramChecker
Please enter the first word: Eleven plus two
Please enter the second word: Twelve plus one
Eleven plus two is an anagram of Twelve plus one

Following is alternate implementation for checking whether two words are anagrams. We iterate through the letters of the first word removing each letter from the second word. Finally if there are no letters remaining in the second word we know that both are anagrams of each other.

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

//Checks whether two words are anagrams of each other in Java
public class AnagramChecker2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Please enter the first word: ");
        String word1 = scanner.nextLine();
        
        System.out.print("Please enter the second word: ");
        String word2 = scanner.nextLine();
        
        if(isAnagram(word1,word2)) {
            System.out.println(word1+" is an anagram of "+word2);
        }else {
            System.out.println(word1+" is NOT an anagram of "+word2);
        }

        scanner.close();
    }

    // Check if two words are anagrams in Java
    // Removes letters in word1 from word2. 
    // If there are no letters left in word2, we know that they are anagrams of each other
    private static boolean isAnagram(String word1, String word2) {
       word1 = word1.replaceAll("\\s", "").toLowerCase();
       word2 = word2.replaceAll("\\s", "").toLowerCase();
       
       // Length of two strings must match!
       if(word1.length()!=word2.length()) {
           return false;
       }
       
       for(int i=0;i<word1.length();i++) {
           // Is there a letter in word2 corresponding to the word1 letter?
           int pos = word2.indexOf(word1.substring(i, i+1));
           if(pos>=0) {
               // Remove the letter!
               word2 = word2.substring(0, pos)+word2.substring(pos+1);
           }else {
               // Letter not found! Hence not an anagram
               return false;
           }
       }
       
       // Finally if word2 is empty, it is an anagram of word1
       if(word2.length()==0) {
           return true;
       }else {
           return false;
       }
    }
    
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply