Check if two given strings are anagram – Java

Q. Write a program to check if the two given string are anagram or not.

Answer:

Anagram:
An anagram is a rearrangement of the letters of one word or phrase to another word or phrase, using all the original letters exactly once.

There is a isAnagram() method which compares two string and matches each and every character of both strings.

AnagramTest.java

import java.util.*;
public class AnagramTest
{
     static void isAnagram(String s1, String s2)
     {
          //Removing white spaces from
          String str1 = s1.replaceAll("\\s", "");
          String str2 = s2.replaceAll("\\s", "");
          boolean status = true;

          if(str1.length() != str2.length())
          {
               status = false;
          }
          else
          {
               char[] s1Array = str1.toLowerCase().toCharArray();
               char[] s2Array = str2.toLowerCase().toCharArray();
               Arrays.sort(s1Array);
               Arrays.sort(s2Array);
               status = Arrays.equals(s1Array, s2Array);
          }
          if(status)
          {
               System.out.println(s1+" and "+s2+" are anagrams");
          }
          else
          {
               System.out.println(s1+" and "+s2+" are not anagrams");
          }
     }
     public static void main(String[] args)
     {
          isAnagram("keEp", "peeK");
          isAnagram("Java", "Vaja");
          isAnagram("Lock", "Clock");
     }
}


Output:

anagram