Below program illustrates how to check if given Strings are anagram or not in Java:
public class AnagramStrings { public static void main(String[] args) { String s1 = "Army"; String s2 = "Mary"; System.out.println("Strings are anagram? " + checkAnagrams(s1, s2)); System.out.println("Strings are anagram? " + checkAnagrams2(s1, s2)); } private static boolean checkAnagrams(String s1, String s2) { if(s1.length() != s2.length()) { return false; } s1 = s1.toLowerCase(); s2 = s2.toLowerCase(); char[] s1Arr = s1.toCharArray(); char[] s2Arr = s2.toCharArray(); Arrays.sort(s1Arr); Arrays.sort(s2Arr); return Arrays.equals(s1Arr, s2Arr); } private static boolean checkAnagrams2(String s1, String s2) { if(s1.length() != s2.length()) { return false; } s1 = s1.toLowerCase(); s2 = s2.toLowerCase(); char[] s1Arr = s1.toCharArray(); for(char ch : s1Arr) { int index = s2.indexOf(ch); if(index == -1) { return false; } else { s2 = s2.substring(0, index) + s2.substring(index+1, s2.length()); } } return s2.isEmpty(); } }