An anagram is a word or phrase that is formed by rearranging the letters of another word or phrase. For example, "listen" and "silent" are anagrams of each other.
To check if two strings are anagrams in Java, you can write a function that compares the characters in the two strings and returns true
if they contain the same characters in the same frequencies, and false
otherwise.
Here is an example of how to implement this in Java:
public static boolean isAnagram(String s1, String s2) { // Check if the strings have the same length if (s1.length() != s2.length()) return false; // Convert the strings to lowercase and sort their characters s1 = s1.toLowerCase(); s2 = s2.toLowerCase(); char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); Arrays.sort(c1); Arrays.sort(c2); // Check if the sorted arrays are equal for (int i = 0; i < c1.length; i++) { if (c1[i] != c2[i]) return false; } return true; }
This function first checks if the two strings have the same length. If they do not, it returns false
as they cannot be anagrams. If the strings have the same length, it converts them to lowercase, sorts their characters in alphabetical order, and checks if the sorted arrays are equal. If they are not equal, the function returns false
. If the loop completes without returning false
, the function returns true
, indicating that the strings are anagrams.
To use this function, you can call it with two strings as arguments, like this:
String s1 = "listen"; String s2 = "silent"; if (isAnagram(s1, s2)) { System.out.println(s1 + " and " + s2 + " are anagrams."); } else { System.out.println(s1 + " and " + s2 + " are not anagrams."); }
This will output "listen and silent are anagrams." to the console.
For more information on anagrams and how to check if two strings are anagrams in Java, you can refer to online resources or books on the subject.