Anagram in Java with Program

In this tutorial, we will know what is anagram in Java and how to check two strings are an anagram or not. Interviewer frequently asks anagram Java program in Java interview. So, let’s understand.

Anagram

An anagram is a word or phrase that, when we rearrange its letter, another new word or phrase creates. For example, the word “secure” is an anagram of “rescue”.

In the dictionary, the meaning of the anagram is a word or phrase formed by rearranging the letters of a different word or phrase.

Other examples of the word anagram are:

  • Listen – > Silent
  • Heart – > Earth
  • Stop – > Pots
  • Keep -> Peek
  • Great Taste! -> Gear at Test!

In Java, two strings are said to be anagrams if they contain the same set of characters but are in a distinct order.

In other words, two strings are anagram if they make a meaningful word by shuffling or rearranging the letters of the string. Remember that a letter has to be used only once.

How to check two Strings are Anagram or not in Java?


There are the following points you must keep to check two strings are anagram or not in Java.

1. Create and initialize two strings, str1 and str2.

2. Find the length of both the strings.

3. Compare the length of the strings.

  • If the length of string is not equal, then display strings are not an anagram.
  • Else, do the following thing:

a) Convert the string into a character array.
b) Sort both the arrays by using the Arrays.sort() method.
c) After sorting, check equality of both strings by using the Arrays.equals() method.
d) Store the value in a variable of boolean type to store the status returned by the equals() method.
e) Now, pass the variable in the if statement. If it returns true, both strings are anagram. Otherwise, not an anagram.

Let’s implement the above important steps in a Java program to check two strings are anagrams of each other or not.

Java program to check if two Strings are Anagram or not


There are several ways to check whether or not the two strings are anagram. But, in this section, we will focus on the following three important ways.

  • Using Arrays Class
  • Using for Loop
  • By using StringBuilder Class

[adinserter block=”5″]

Using Arrays Class

Let’s write a Java program to check if the two strings are anagram or not. In this program, we will use two methods: Arrays.sort() and Arrays.equals().

Program code 1:

package stringPrograms;
import java.util.Arrays;
public class AnagramStringExample {
public static void main(String[] args) 
{
// Create two string literals.	 
   String str1 = "Heart";
   String str2 = "Earth";

// Convert both strings into the lower case.       
   str1 = str1.toLowerCase();
   str2 = str2.toLowerCase();

// Check the length of both strings are equal or not.
   if(str1.length() == str2.length()) {
// Convert strings into char array.
   char[] charArray1 = str1.toCharArray();
   char[] charArray2 = str2.toCharArray();

// Sort the char array using Arrays.sort() method.
   Arrays.sort(charArray1);
   Arrays.sort(charArray2);

// If sorted char arrays are equal, the string is anagram
   boolean result = Arrays.equals(charArray1, charArray2);
// Inner if else statement.   
   if(result) {
      System.out.println(str1 + " and " + str2 + " are anagram.");
   }
    else {
      System.out.println(str1 + " and " + str2 + " are not anagram.");
    }
   }
// else of outer if statement.   
   else {
         System.out.println(str1 + " and " + str2 + " are not anagram.");
       }
   }
}
Output:
      heart and earth are anagram.

In this Java program, we have created two strings named str1 and str2. First, we have converted both strings to the lowercase because Java is case sensitive and R and r are two difference characters in Java.

In the above code,

  • str1.toCharArray() converts the string into a char array
  • Arrays.sort() sorts both the char arrays
  • Arrays.equal() checks if the sorted char array is equal. If sorted arrays are equal, then both strings are anagram in Java.

[adinserter block=”2″]

Note: Arrays.sort() method compares two characters with ASCII value. Characters R and r are not equal. Hence, convert strings to the same case.


Let’s understand another approach to check whether two strings are anagram.

Program code 2:

package stringPrograms;
import java.util.Arrays;
public class AnagramStringExample 
{
// Create a static method to check if the strings are anagram or not.
   static void isAnagram(String str1, String str2)   
   {    
// Remove white spaces from strings.  
   String s1 = str1.replaceAll("\\s", "");     
   String s2 = str2.replaceAll("\\s", "");    

// Convert both strings into lower case.       
   str1 = s1.toLowerCase();
   str2 = s2.toLowerCase();

// Check the length of both strings are equal or not.
   if(s1.length() == s2.length()) {
// Convert strings into char array.
   char[] charArray1 = s1.toCharArray();
   char[] charArray2 = s2.toCharArray();

// Sort the char array using Arrays.sort() method.
   Arrays.sort(charArray1);
   Arrays.sort(charArray2);

// If sorted char arrays are equal, the string is anagram
   boolean result = Arrays.equals(charArray1, charArray2);
// Inner if else statement.   
   if(result) {
	 System.out.println(str1 + " and " + str2 + " are anagram.");
   }
   else {
     System.out.println(str1 + " and " + str2 + " are not anagram.");
   }
  } // end outer if statement.
// else of outer if statement.   
   else {
      System.out.println(str1 + " and " + str2 + " are not anagram.")
   }
  } // end outer else statement.
public static void main(String[] args) 
 {
// Calling static method.     
   isAnagram("HEART", "EARTH");    
   isAnagram("STOP", "POTS");    
   isAnagram("H ELLO", "OH E LL");   
   }
}
Output:
      heart and earth are anagram.
      stop and pots are anagram.
      hello and ohell are anagram.

Java Program to take string inputs from users and check if the strings are anagram


Program code 3:

package stringPrograms;
import java.util.Arrays;
import java.util.Scanner;
public class AnagramStringExample {  
public static void main(String[] args) 
{
// Create an object of Scanner class to take an input from the user.
   Scanner input = new Scanner(System.in);

// Take input from users.
   System.out.print("Enter your first String: ");
// This statement will read the next line of text input from the source.
   String str1 = input.nextLine();
   System.out.print("Enter your second String: ");
   String str2 = input.nextLine();
   
// Remove white spaces from strings.  
   String s1 = str1.replaceAll("\\s", "");     
   String s2 = str2.replaceAll("\\s", "");    

// Convert both strings into lower case.       
   str1 = s1.toLowerCase();
   str2 = s2.toLowerCase();

// Check the length of both strings are equal or not.
   if(s1.length() == s2.length()) {
// Convert strings into char array.
   char[] charArray1 = s1.toCharArray();
   char[] charArray2 = s2.toCharArray();
   
// Sort the char array using Arrays.sort() method.
   Arrays.sort(charArray1);
   Arrays.sort(charArray2);

// If sorted char arrays are equal, the string is anagram
   boolean result = Arrays.equals(charArray1, charArray2);
// Inner if else statement.   
   if(result) {
	 System.out.println(str1 + " and " + str2 + " are anagram.");
   }
   else {
      System.out.println(str1 + " and " + str2 + " are not anagram.");
   }
  }
// else of outer if statement.   
   else {
      System.out.println(str1 + " and " + str2 + " are not anagram.");
   }
   }   
 }
Output:
      Enter your first String: KEEP
      Enter your second String: PEEK
      keep and peek are anagram.

Using For Loop

Let’s create a Java Program to check the strings are anagram or not, by using for loop. In this program, we will take string input from the user using Java Scanner class.

Program code 4:

package stringPrograms;
import java.util.Scanner;
public class AnagramStringExample 
{ 
// Create a method to check if the strings are anagram or not.
   public static boolean isAnagram(String str1, String str2) 
   {
  // Check the length of both strings are equal or not.
     if(str1.length() != str2.length()) 
     {
     // Returns false if the strings are not of equal length.     
        return false;  
     }     
  // Convert strings into char array.
     char[] charArray1 = str1.toCharArray();
  // Iterating using for loop over the array.  
     for (char c : charArray1)   
     {  
     // Finds the index.      
        int index = str2.indexOf(c);  
        if (index != -1) {  
       // Call substring() method returns a new string that is a substring of this string.  
          str2 = str2.substring(0, index) + str2.substring(index + 1, str2.length());   
        }
       else {  
           return false;  
       } 
     }
     return str2.isEmpty();  
 }
public static void main(String[] args) 
{
// Create an object of Scanner class.
   Scanner input = new Scanner(System.in);
// Take input from users.
   System.out.print("Enter your first String: ");
   String str1 = input.nextLine();
   System.out.print("Enter your second String: ");
   String str2 = input.nextLine();
   
// Calling method.
   boolean status = isAnagram(str2, str2);
   System.out.println(status);
   }   
 }
Output:
      Enter your first String: HEART
      Enter your second String: EARTH
      true

Using StringBuilder Class

Using StringBuilder class is the third way to check that the two strings are anagram or not. Let’s write a program for it.

Program code 5:

package stringPrograms;
import java.util.Scanner;
public class AnagramStringExample 
{ 
// Create a method to check if the strings are anagram or not.
   public static boolean isAnagram(String str1, String str2) 
   {
   // Check the length of both strings are equal or not.
      if(str1.length() != str2.length()) {
      // Returns false if the strings are not of equal length.     
         return false;  
      }     
   // Convert strings into char array.
      char[] charArray1 = str1.toCharArray();
      StringBuilder sb = new StringBuilder(str2);

   // Iterating using for loop over the array.  
      for (char c : charArray1)   
      {  
     // Find the index of character.    
        int index = sb.indexOf("" +c);  
        if (index != -1) {  
        // Delete character at the specified index		
           sb.deleteCharAt(index);    
        }
        else {  
           return false;  
        } 
      }  
   // Find length of character.
      return sb.length() == 0 ? true : false;  
  }
public static void main(String[] args) 
{
// Create an object of Scanner class.
   Scanner input = new Scanner(System.in);
// Take input from users.
   System.out.print("Enter your first String: ");
   String str1 = input.nextLine();
   System.out.print("Enter your second String: ");
   String str2 = input.nextLine();
   
// Calling method.
   boolean status = isAnagram(str1, str2);
   System.out.println(status);
   }   
 }
Output:
      Enter your first String: HELLO
      Enter your second String: OLLEH
      true

In this tutorial, we have discussed anagram in Java with the help of a variety of example programs. Hope that you will have understood how to check if the two strings are anagrams. In the next, we will understand how to swap two strings in Java.
Thanks for reading!!!

⇐ Prev Next ⇒