Java program to check if two strings are anagram
Here's an example Java program to check if two strings are anagram:
import java.util.Arrays; public class AnagramChecker { public static void main(String[] args) { String str1 = "silent"; String str2 = "listen"; 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) { // Remove all whitespaces and convert the strings to lowercase str1 = str1.replaceAll("\\s", "").toLowerCase(); str2 = str2.replaceAll("\\s", "").toLowerCase(); // Check if the lengths of the strings are equal if (str1.length() != str2.length()) { return false; } // Convert the strings to character arrays and sort them char[] charArray1 = str1.toCharArray(); char[] charArray2 = str2.toCharArray(); Arrays.sort(charArray1); Arrays.sort(charArray2); // Compare the sorted character arrays return Arrays.equals(charArray1, charArray2); } }
This program uses a areAnagrams
method that takes two strings as input and returns true
if they are anagrams, and false
otherwise. To check if the two strings are anagrams, the method first removes all whitespace characters and converts the strings to lowercase to make the comparison case-insensitive. It then checks if the lengths of the strings are equal, since anagrams have the same number of characters. If the lengths are not equal, the method returns false
.
If the lengths are equal, the method converts the strings to character arrays and sorts them using the Arrays.sort
method. The Arrays.equals
method is then used to compare the sorted character arrays. If they are equal, the method returns true
, which indicates that the two strings are anagrams.
In the main method, the areAnagrams
method is called with two sample strings "silent"
and "listen"
. If they are anagrams, the program prints a message indicating that they are anagrams, otherwise, it prints a message indicating that they are not anagrams.
Note that this program assumes that the input strings contain only ASCII characters. If the input strings contain Unicode characters, you may need to use a different approach for comparing the characters.