Anagram Check
Check whether two strings are anagrams of each other.
IntermediateTopic: Module 4: String Programs
Java Anagram Check Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first string: ");
String s1 = sc.nextLine().replaceAll("\\s+", "").toLowerCase();
System.out.print("Enter second string: ");
String s2 = sc.nextLine().replaceAll("\\s+", "").toLowerCase();
if (s1.length() != s2.length()) {
System.out.println("Not Anagram");
} else {
char[] a1 = s1.toCharArray();
char[] a2 = s2.toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
if (Arrays.equals(a1, a2)) {
System.out.println("Anagram");
} else {
System.out.println("Not Anagram");
}
}
sc.close();
}
}Output
Enter first string: listen Enter second string: silent Anagram
Understanding Anagram Check
We normalize, sort characters of both strings, and compare arrays.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.