Anagram Checker in Java


Anagram Checker in Java

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, “listen” is an anagram of “silent”.

Program Structure

The Java program provided below checks if two strings are anagrams of each other. The program follows these steps:

  1. Remove any spaces and convert both strings to lowercase for a case-insensitive comparison.
  2. Check if the lengths of the two strings are equal. If not, they cannot be anagrams.
  3. Sort the characters of both strings and compare the sorted results.
  4. If the sorted strings are identical, the original strings are anagrams.

Java Program

import java.util.Arrays;

public class AnagramChecker {

    /**
     * Checks if two strings are anagrams.
     * 
     * @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 spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();
        
        // Check if lengths are different
        if (str1.length() != str2.length()) {
            return false;
        }
        
        // Convert strings to character arrays
        char[] arr1 = str1.toCharArray();
        char[] arr2 = str2.toCharArray();
        
        // Sort the character arrays
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        
        // Compare sorted arrays
        return Arrays.equals(arr1, arr2);
    }

    public static void main(String[] args) {
        // Test cases
        String string1 = "Listen";
        String string2 = "Silent";

        // Check if the strings are anagrams
        boolean result = areAnagrams(string1, string2);

        // Output result
        if (result) {
            System.out.println(string1 + " and " + string2 + " are anagrams.");
        } else {
            System.out.println(string1 + " and " + string2 + " are not anagrams.");
        }
    }
}

Explanation of the Program

The program contains a method areAnagrams that performs the following actions:

  • Normalization: It removes any spaces from the strings and converts them to lowercase to ensure the comparison is case-insensitive.
  • Length Check: If the lengths of the two strings are different, they cannot be anagrams, so the method returns false.
  • Sorting: Both strings are converted to character arrays, which are then sorted.
  • Comparison: The sorted character arrays are compared. If they are equal, the original strings are anagrams.

The main method contains test cases that demonstrate the functionality of the areAnagrams method.


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 :)