In this tutorial, we are going to learn to write Java Program to check whether two given strings are anagrams or not?
What is Anagram?
Two Strings are called Anagram if they contain the same characters but the order may difference.
For Example:
tomatao and mataoto are the anagram
Anagram Program in Java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Give First String Input: ");
String str1= sc.nextLine();
Scanner sc1= new Scanner(System.in);
System.out.print("Give Second String Input: ");
String str2= sc.nextLine();
if(anagramCheck(str1,str2)){
System.out.print("String are anagram");
}else{
System.out.print("String are not anagram");
}
}
public static boolean anagramCheck(String str1, String str2){
boolean status = false;
if (str1.length() != str2.length()) {
status = false;
} else {
char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
status = Arrays.equals(arr1, arr2);
}
return status;
}
}
Output 1:
Give First String Input: moon
Give Second String Input: noom
String are anagram
Output 2:
Give First String Input: Potato
Give Second String Input: Tomato
String are not anagram