1. Introduction
An anagram is a word or phrase that is created by rearranging the letters of another, using all the original letters exactly once. In this post, we will learn how to create a Java program to check if two strings are anagrams of each other.
2. Program Steps
1. Define the main method to serve as the entry point of our program.
2. Take two input strings that we want to check for anagrams.
3. Convert the strings to character arrays.
4. Sort both character arrays.
5. Compare the sorted arrays.
6. If both sorted arrays are equal, then the input strings are anagrams, else they are not.
7. Print the result.
3. Code Program
public class AnagramChecker {
public static void main(String[] args) {
// Step 2: Take two input strings
String str1 = "listen";
String str2 = "silent";
// Step 3: Convert the strings to character arrays
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
// Step 4: Sort both character arrays
java.util.Arrays.sort(charArray1);
java.util.Arrays.sort(charArray2);
// Step 5: Compare the sorted arrays
boolean areAnagrams = java.util.Arrays.equals(charArray1, charArray2);
// Step 7: Print the result
if (areAnagrams) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
}
}
Output:
listen and silent are anagrams.
4. Step By Step Explanation
– Step 1: The main method is defined as the starting point of the program.
– Step 2: We define two input strings, str1 and str2, that we want to check for anagrams.
– Step 3: We convert the strings to character arrays charArray1 and charArray2.
– Step 4: We sort both character arrays using Arrays.sort() method.
– Step 5: We compare the sorted arrays using Arrays.equals() method. If they are equal, it means the input strings are anagrams.
– Step 7: Based on the comparison, we print whether the input strings are anagrams or not.
This method ensures that we can effectively check if two strings are anagrams by comparing their sorted character arrays.