Java Program To Check Whether Two Strings Are An Anagram Or Not

Introduction

According to Wikipedia, "An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once."

For example

  • Worth is an anagram of throw.
  • Race is an anagram of care.

Algorithm

Step 1

Read Input String(Str1, Str2)

Step 2

Convert Both String Into Char Array

Step 3

If Str1(Length) Is Not Equal To Str2(Length) Then Print Not An Anagram And Exit

Else Apply Bubble Sort On Both Char Array

Step 4

Convert Both Char Array To String (Str3, Str4)

STEP 5

If Str3 Is Equal To Str4 Then Print An Anagram 

Else Print Not An Anagram

Step 6

Exit

Java Program to check if two strings are an anagram or not

import java.util.*;

class test{
	public static void main(String args[]){
		String str1,str2;
		System.out.println("Enter the two String value");
		Scanner sc=new Scanner(System.in);
		
		//Read Input Data
		str1=sc.nextLine();
		str2=sc.nextLine();
		
		//convert strings into char array
		char arr1[]=str1.toCharArray();
		char arr2[]=str2.toCharArray();
		
		/*
         if both string lengths are not equal then 
         strings are not anagram with each other
         otherwise else part executed
        */
		if(arr1.length!=arr2.length){
		System.out.println("Strings are not an anagram");
		}
		else{ 

		    // Apply Bubble Sort Algorithm on both char array
			for(int i=0;i<arr1.length;i++){
				for(int j=i+1;j<arr1.length-1;j++){
					if(arr1[i]>arr1[j]){
					char temp=arr1[i];
					arr1[i]=arr1[j];
					arr1[j]=temp;
					}
			 		
					if(arr2[i]>arr2[j]){
					char temp=arr2[i];
					arr2[i]=arr2[j];
					arr2[j]=temp;
					}
					
				}
			}
			
			//Convert char array into string
			String str3=String.valueOf(arr1);
			String str4=String.valueOf(arr2);
			
			/*
            check if both sorted strings are equal or not.
            if they are equal then strings are an anagram with each other
            else strings are not anagram with each other
            */

			if(str3.equals(str4)){
			System.out.println("input strings are an anagram with each other");
			}
			else{
			System.out.println("input strings are not an anagram with each other");
			}  
		}
		
	}
}	

Output

  

Conclusion

In this blog, we have seen how we can check whether two strings are anagrams or not in java.

Thanks for reading and hope you like it. If you have any suggestions or queries on this blog, please share your thoughts.