Here's a Java program to check whether two strings are anagrams or not:
import java.util.Arrays;
public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
// Remove spaces and convert strings to lowercase
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
// If lengths are not equal, they can't be anagrams
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 sorted arrays
return Arrays.equals(charArray1, charArray2);
}
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
}
}
This program first removes spaces and converts both input strings to lowercase to ensure case-insensitivity. Then, it checks if the lengths of the strings are equal. If not, they cannot be anagrams. After that, it converts both strings into character arrays, sorts them, and finally compares them using `Arrays.equals()`. If the sorted arrays are equal, the strings are anagrams.