Java Program to check whether two Strings are an anagram or not.

Java 8Object Oriented ProgrammingProgramming

According to wiki “An anagram is word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.”

To compare whether two strings are anagrams check if their lengths are equal? If so, convert these two strings into character arrays then, sort them and compare them using the sort() method of the Arrays class, if both are equal then given two strings are anagrams.

Example

Live Demo

import java.util.Arrays;
public class AnagramSample  {
   public static void main(String args[]) {
      String str1 = "recitals";
      String str2 = "articles";

      if (str1.length()==str2.length()) {
         char[] arr1 = str1.toCharArray();
         Arrays.sort(arr1);
         System.out.println(Arrays.toString(arr1));
         char[] arr2 = str2.toCharArray();
         Arrays.sort(arr2);
         System.out.println(Arrays.toString(arr2));
         System.out.println(Arrays.equals(arr1, arr2));
         if(arr1.equals(arr2)) {
            System.out.println("Given strings are anagrams");
         } else {
            System.out.println("Given strings are not anagrams");
         }
      }
   }
}

Output

[a, c, e, i, l, r, s, t]
[a, c, e, i, l, r, s, t]
true
Given strings are not anagrams
raja
Published on 12-Feb-2018 10:31:58
Advertisements