Question:
How to test if two words are anagram using Arrays.sort()?
Code:
import java.util.*; public class Anagram { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter first word: "); String word1 = sc.nextLine(); System.out.print("Enter second word: "); String word2 = sc.nextLine(); System.out.println("Anagram: " + isAnagram(word1,word2)); } // Test if two words are Anagram using Arrays.sort() public static boolean isAnagram(String word1, String word2) { word1 = word1.toLowerCase(); word2 = word2.toLowerCase(); char[] char1 = word1.toCharArray(); char[] char2 = word2.toCharArray(); Arrays.sort(char1); Arrays.sort(char2); return Arrays.equals(char1, char2); } }
Output:
$ java Anagram Enter first word: Angel Enter second word: Glean Anagram: true $ java Anagram Enter first word: bob Enter second word: bobby Anagram: false