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 theareAnagrams
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.