import java.util.Arrays;
public class AnagramChecker {
public static void main(String[] args) {
String str1 = "restful";
String str2 = "fluster";
if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams");
}
}
public static boolean areAnagrams(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
}
restful and fluster are anagrams
str1
and str2
. We then call the areAnagrams()
method, which takes two string arguments str1
and str2
and returns a boolean value indicating whether the two strings are anagrams of each other.areAnagrams()
method first checks whether the lengths of the two strings are equal. If they are not, it returns false
. Otherwise, it converts the strings to character arrays using the toCharArray()
method, and sorts the arrays using the Arrays.sort()
method. It then uses the Arrays.equals()
method to compare the sorted arrays. If they are equal, it returns true
; otherwise, it returns false
.