Anagram Checker Program in Java

Introduction

This program demonstrates how to check if two strings are anagrams of each other in Java. Two strings are considered anagrams if they contain the same characters in the same frequency, but arranged differently.

Java Program


import java.util.Arrays;

/**
 * AnagramChecker class to check if two strings are anagrams.
 */
public class AnagramChecker {
    
    /**
     * Checks if two strings are anagrams of each other.
     * 
     * @param str1 The first string.
     * @param str2 The second string.
     * @return True if the strings are anagrams, false otherwise.
     */
    public static boolean areAnagrams(String str1, String str2) {
        // Remove any whitespace and convert strings to lower case
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();
        
        // Check if lengths of the strings are different
        if (str1.length() != str2.length()) {
            return false;
        }

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

        // Sort the character arrays
        Arrays.sort(charArray1);
        Arrays.sort(charArray2);

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

    /**
     * Main method to test the anagram checker.
     * 
     * @param args Command line arguments.
     */
    public static void main(String[] args) {
        // Example strings
        String str1 = "Listen";
        String str2 = "Silent";

        // Check if the strings are anagrams
        boolean result = areAnagrams(str1, str2);

        // Display the result
        if (result) {
            System.out.println(str1 + " and " + str2 + " are anagrams.");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams.");
        }
    }
}

Explanation

The program consists of a class AnagramChecker with two methods:

  • areAnagrams: This method takes two strings as input and returns a boolean indicating whether they are anagrams. It removes any whitespace, converts the strings to lowercase, checks if the lengths are different, converts the strings to character arrays, sorts the arrays, and compares them.
  • main: This is the entry point of the program. It defines two example strings, calls the areAnagrams method to check if they are anagrams, and prints the result.

Key Points:

  • The strings are first processed to remove whitespace and convert to lowercase to ensure the comparison is case-insensitive and ignores spaces.
  • If the lengths of the strings differ, they cannot be anagrams, and the method returns false.
  • The character arrays of the strings are sorted and then compared using Arrays.equals to determine if the strings are anagrams.
  • The program prints a message indicating whether the given strings are anagrams.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)