Write Code To Check If Two Strings Are Anagram Or Not In Java Program
Anagrams are words or phrases formed by rearranging the letters of another. In this article, you will learn how to write Java programs to efficiently check if two given strings are anagrams of each other.
Problem Statement
The core problem is to determine if two input strings contain the exact same characters with the same frequencies, regardless of their order. This means that if you rearrange the characters of the first string, you should be able to form the second string, and vice-versa. This check is case-sensitive and also considers spaces and special characters unless explicitly handled.
For example, "listen" and "silent" are anagrams. "hello" and "bello" are not. "Debit Card" and "Bad Credit" are anagrams if spaces and case are ignored.
Example
Consider the strings "listen" and "silent".
The program should output:
"listen" and "silent" are anagrams.
Background & Knowledge Prerequisites
To effectively understand the solutions presented, readers should have a basic understanding of:
- Java Strings: How to declare, manipulate, and compare strings.
- Character Arrays: Converting strings to character arrays and vice-versa.
- Arrays: Basic array operations, including sorting and iteration.
- Loops:
forloops for iterating through strings or arrays. - Conditional Statements:
if-elsestructures for logic. - Methods: Defining and calling static methods.
Relevant imports needed will primarily be for utility classes like java.util.Arrays for sorting or java.util.Scanner for user input (though not strictly necessary for the core logic).
Use Cases or Case Studies
Anagram checking has several practical applications across various domains:
- Word Games and Puzzles: Validating user input in games like Scrabble or finding anagrams for cryptic crosswords.
- Data Validation: Ensuring transformed data retains its original character set, useful in some encryption or obfuscation scenarios.
- Educational Tools: Helping students understand word formation and character manipulation.
- Lexicographical Analysis: In natural language processing, identifying words with similar character compositions.
- Bioinformatics: Comparing DNA sequences or protein structures where character order might be rearranged but content remains similar.
Solution Approaches
We will explore two robust approaches to check for anagrams in Java:
- Sorting Characters: This method involves converting both strings to character arrays, sorting them, and then comparing the sorted arrays.
- Using a Frequency Array (or Map): This method counts the occurrences of each character in both strings and then compares the counts.
Approach 1: Sorting Characters
This approach relies on the principle that if two strings are anagrams, their sorted character sequences must be identical.
- Summary: Convert strings to character arrays, sort both arrays, and then compare them.
// Anagram Checker (Sorting)
import java.util.Arrays; // Required for Arrays.sort() and Arrays.equals()
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
/**
* Checks if two strings are anagrams by sorting their characters.
* Ignores case and non-alphabetic characters.
*
* @param str1 The first string.
* @param str2 The second string.
* @return true if the strings are anagrams, false otherwise.
*/
public static boolean areAnagramsUsingSort(String str1, String str2) {
// Step 1: Handle null or empty strings
if (str1 == null || str2 == null) {
return false;
}
if (str1.isEmpty() && str2.isEmpty()) {
return true;
}
// Step 2: Normalize strings (remove spaces, convert to lowercase)
// This makes the comparison case-insensitive and ignores spaces.
String processedStr1 = str1.replaceAll("\\\\s", "").toLowerCase();
String processedStr2 = str2.replaceAll("\\\\s", "").toLowerCase();
// Step 3: Check if lengths are different after processing
if (processedStr1.length() != processedStr2.length()) {
return false;
}
// Step 4: Convert strings to character arrays
char[] charArray1 = processedStr1.toCharArray();
char[] charArray2 = processedStr2.toCharArray();
// Step 5: Sort both character arrays
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// Step 6: Compare the sorted character arrays
// Arrays.equals() efficiently compares the contents of two arrays
return Arrays.equals(charArray1, charArray2);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("--- Anagram Checker (Sorting Method) ---");
System.out.print("Enter first string: ");
String s1 = scanner.nextLine();
System.out.print("Enter second string: ");
String s2 = scanner.nextLine();
boolean isAnagram = areAnagramsUsingSort(s1, s2);
if (isAnagram) {
System.out.println("\\"" + s1 + "\\" and \\"" + s2 + "\\" are anagrams.");
} else {
System.out.println("\\"" + s1 + "\\" and \\"" + s2 + "\\" are NOT anagrams.");
}
scanner.close();
}
}
- Sample Output:
--- Anagram Checker (Sorting Method) ---
Enter first string: Listen
Enter second string: Silent
"Listen" and "Silent" are anagrams.
--- Anagram Checker (Sorting Method) ---
Enter first string: Debit Card
Enter second string: Bad Credit
"Debit Card" and "Bad Credit" are anagrams.
--- Anagram Checker (Sorting Method) ---
Enter first string: hello
Enter second string: world
"hello" and "world" are NOT anagrams.
- Stepwise Explanation:
- Handle Null/Empty: The method first checks for null or empty strings to prevent
NullPointerExceptionsand handle edge cases gracefully. - Normalize Strings: Both input strings are converted to lowercase using
toLowerCase()and all whitespace characters are removed usingreplaceAll("\\s", ""). This ensures a case-insensitive and space-agnostic comparison. - Length Check: If the lengths of the processed strings are different, they cannot be anagrams, so
falseis returned immediately. - Convert to Char Arrays: Each processed string is converted into a
chararray usingtoCharArray(). - Sort Arrays: The
Arrays.sort()method is used to sort the characters in both arrays alphabetically. - Compare Sorted Arrays: Finally,
Arrays.equals()is used to compare the two sorted character arrays. If they are identical, the strings are anagrams; otherwise, they are not.
Approach 2: Using a Frequency Array
This approach involves counting the frequency of each character in both strings. If the character counts match for all characters, the strings are anagrams.
- Summary: Initialize an integer array (representing character counts), iterate through both strings to adjust counts, and check if all counts are zero at the end.
// Anagram Checker (Frequency Array)
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
/**
* Checks if two strings are anagrams using a frequency array.
* Ignores case and non-alphabetic characters.
* Assumes ASCII characters for array size.
*
* @param str1 The first string.
* @param str2 The second string.
* @return true if the strings are anagrams, false otherwise.
*/
public static boolean areAnagramsUsingFrequencyArray(String str1, String str2) {
// Step 1: Handle null or empty strings
if (str1 == null || str2 == null) {
return false;
}
if (str1.isEmpty() && str2.isEmpty()) {
return true;
}
// Step 2: Normalize strings (remove spaces, convert to lowercase)
String processedStr1 = str1.replaceAll("\\\\s", "").toLowerCase();
String processedStr2 = str2.replaceAll("\\\\s", "").toLowerCase();
// Step 3: Check if lengths are different after processing
if (processedStr1.length() != processedStr2.length()) {
return false;
}
// Step 4: Create a frequency array for characters (assuming ASCII)
// Size 256 for all possible ASCII character values
int[] charCounts = new int[256];
// Step 5: Iterate through the first string and increment character counts
for (char c : processedStr1.toCharArray()) {
charCounts[c]++;
}
// Step 6: Iterate through the second string and decrement character counts
for (char c : processedStr2.toCharArray()) {
charCounts[c]--;
}
// Step 7: Check if all character counts are zero
// If they are, it means all characters matched in frequency
for (int count : charCounts) {
if (count != 0) {
return false; // Mismatch found
}
}
// All counts are zero, so they are anagrams
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("--- Anagram Checker (Frequency Array Method) ---");
System.out.print("Enter first string: ");
String s1 = scanner.nextLine();
System.out.print("Enter second string: ");
String s2 = scanner.nextLine();
boolean isAnagram = areAnagramsUsingFrequencyArray(s1, s2);
if (isAnagram) {
System.out.println("\\"" + s1 + "\\" and \\"" + s2 + "\\" are anagrams.");
} else {
System.out.println("\\"" + s1 + "\\" and \\"" + s2 + "\\" are NOT anagrams.");
}
scanner.close();
}
}
- Sample Output:
--- Anagram Checker (Frequency Array Method) ---
Enter first string: Program
Enter second string: grampro
"Program" and "grampro" are anagrams.
--- Anagram Checker (Frequency Array Method) ---
Enter first string: hello
Enter second string: olleh
"hello" and "olleh" are anagrams.
--- Anagram Checker (Frequency Array Method) ---
Enter first string: Java
Enter second string: C++
"Java" and "C++" are NOT anagrams.
- Stepwise Explanation:
- Handle Null/Empty: Similar to the sorting approach, null or empty strings are handled.
- Normalize Strings: Both strings are normalized by converting to lowercase and removing spaces.
- Length Check: An immediate return
falseif lengths differ, as anagrams must have the same length. - Create Frequency Array: An integer array
charCountsof size 256 is created. This array will store the frequency of each ASCII character (0-255). - Increment Counts (First String): The code iterates through the first processed string. For each character, its ASCII value is used as an index to increment the corresponding count in
charCounts. - Decrement Counts (Second String): The code then iterates through the second processed string. For each character, its ASCII value is used as an index to decrement the corresponding count in
charCounts. - Verify Counts: Finally, the
charCountsarray is checked. If all elements incharCountsare zero, it means that every character in the first string had a corresponding match (and was "canceled out") by a character in the second string, making them anagrams. If any count is non-zero, it indicates a character mismatch in frequency.
Conclusion
Checking if two strings are anagrams is a fundamental string manipulation problem with various applications. Both the sorting approach and the frequency array approach provide effective solutions. The sorting method is generally easier to understand and implement due to the Arrays.sort() utility, while the frequency array method offers better time complexity, especially for very long strings, as it avoids a full sort (which typically has O(N log N) complexity) and instead uses O(N) linear passes. The choice between them often depends on performance requirements and code readability preferences.
Summary
- Anagram Definition: Two strings are anagrams if they contain the same characters with the same frequencies, regardless of order.
- Normalization: For practical anagram checks, it's often essential to normalize strings by converting to lowercase and removing spaces or punctuation.
- Sorting Approach: Convert strings to character arrays, sort them, and compare. Simple and readable.
- Frequency Array Approach: Use an integer array (or a
HashMapfor Unicode) to count character occurrences. More efficient for large inputs. - Length Check: An essential initial step for both approaches, as anagrams must have identical lengths.