In this tutorial, you will learn the writing program in to check string is anagrams or not in java.
How this Java program will behave?
This Program will take two String as an input. And after the comparison it will return output.
If the string is anagram then it will return “Given Strings are anagram” as an output.
And if Strings are not anagram then it will return “Strings are not anagram”.
Anagrams program in java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Please give First String : ");
String str1= sc.nextLine();
Scanner sc1= new Scanner(System.in);
System.out.print("Please give Second String : ");
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
Please give First String : ELAVARASAN
Please give Second String : NASARAVALE
String are anagram