Write a Java program to check if the two strings are anagrams.
Certainly! An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. To check if two strings are anagrams in Java, you can follow these steps:
Here’s a simple Java program that implements this logic:
import java.util.Arrays;
import java.util.Scanner;
public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
// Remove whitespace and convert to lowercase
str1 = str1.replaceAll("\\s+", "").toLowerCase();
str2 = str2.replaceAll("\\s+", "").toLowerCase();
// If lengths are not the same, they cannot be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Convert strings to character arrays
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
// Sort the character arrays
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// Compare sorted arrays
return Arrays.equals(charArray1, charArray2);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String firstString = scanner.nextLine();
System.out.print("Enter the second string: ");
String secondString = scanner.nextLine();
if (areAnagrams(firstString, secondString)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
scanner.close();
}
}
AnagramChecker.java
.javac AnagramChecker.java
.java AnagramChecker
.Input: listen
and silent
Output: The strings are anagrams.
Input: hello
and world
Output: The strings are not anagrams.
This program effectively checks for anagrams by sorting the characters of both strings and comparing them.