Java Program to determine whether two strings are the anagram

Two Strings are called the anagram if they contain the same characters. However, the order or sequence of the characters can be different.

In this program, our task is to check for two strings that, they are the anagram or not. For this purpose, we are following a simpler approach.

First of all, Compare the length of the strings, if they are not equal in the length then print the error message and make an exit, otherwise, convert the string into lower-case for the easy comparisons. Sort both the strings using bubble sort or other sorting methods. If the strings are found to be identical after sorting, then print that strings are anagram otherwise print that strings are not the anagram.

For programming, follow the algorithm given below:

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE str1 = “Brag”, str2 = “Grab”.
  • STEP 3: CONVERT str1, str2 to lower-case.
  • STEP 4: IF length of str1, str2 are not equal then PRINT “Not Anagram”
    else go to Step 5
  • STEP 5: CONVERT str1, str2 to character arrays.
  • STEP 6: SORT the arrays.
  • STEP 7: COMPARE the arrays, IF equal then PRINT “Anagram”
    else
    PRINT “Not Anagram”
  • STEP 8: END

Program:

  1. import java.util.Arrays;  
  2. public class Anagram {  
  3.     public static void main (String [] args) {  
  4.         String str1=”Brag”;  
  5.         String str2=”Grab”;  
  6.   
  7.         //Converting both the string to lower case.  
  8.         str1 = str1.toLowerCase();  
  9.         str2 = str2.toLowerCase();  
  10.   
  11.         //Checking for the length of strings  
  12.         if (str1.length() != str2.length()) {  
  13.             System.out.println(“Both the strings are not anagram”);  
  14.         }  
  15.         else {  
  16.             //Converting both the arrays to character array  
  17.             char[] string1 = str1.toCharArray();  
  18.             char[] string2 = str2.toCharArray();  
  19.   
  20.             //Sorting the arrays using in-built function sort ()  
  21.             Arrays.sort(string1);  
  22.             Arrays.sort(string2);  
  23.   
  24.             //Comparing both the arrays using in-built function equals ()  
  25.             if(Arrays.equals(string1, string2) == true) {  
  26.                 System.out.println(“Both the strings are anagram”);  
  27.             }  
  28.             else {  
  29.                 System.out.println(“Both the strings are not anagram”);  
  30.             }  
  31.         }  
  32.     }  
  33. }   

Output:

Both the strings are anagram

Leave a Comment