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:
- Remove any spaces and convert both strings to lowercase for a case-insensitive comparison.
- Check if the lengths of the two strings are equal. If not, they cannot be anagrams.
- Sort the characters of both strings and compare the sorted results.
- 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.