Write a Java program to check whether two strings are an Anagram of each other or not.

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.


We can check anagram in java in multiple ways.

Using substring()

First, we will check if two strings are of the same length or not. If not then they can never be the anagram of each other.

We will loop through each character of the first string and will find the index of that character in the second string using the indexOf() method. If indexOf() method returns -1 then that character is not present in the second string so we stop our process because the string is not an anagram of each other.

If the character is present in the second string then, we will use substring() method to strip off the character at index position from second string.

We will repeat this process for every character of the first string. After the process, we will check if the second string is empty or not. If yes then it is an anagram else it is not.


Using StringBuffer class

We are using the same method as in the above program but instead of substring() we will use StringBuffer class because StringBuffer makes string mutable, hence we can remove or update any character of the StringBuffer string.


Using Character Array

In this technique, we will first convert both the strings into its corresponding char array and the will sort them using Arrays.sort() method.

Now we will check for the equality of the two arrays using Arrays.equals(), if they are equal then they are Anagram.


If you have any doubts or suggestion then comment below.

Leave a Reply