What is an anagram in Java?

In this section, we will discuss what is anagram in Java and how to check if the given string is an anagram or not. The anagram Java program is frequently asked in Java interviews.

Anagram

The dictionary meaning of the word anagram is a word or phrase formed by rearranging the letters.

Two strings are said to be anagrams if they make a meaningful word by rearranging or shuffling the letters of the string. In other words, we can say that two strings are anagrams if they contain the same characters but in a different order. Note that a letter has to be used only once.

Example of Anagram

There are several anagram words some of them are:

LISTEN - > SILENT

HEART - > EARTH

LIVES - > ELVIS

KEEP -> PEEK

TABLE - >BLEAT

What is an anagram in Java

How to check two strings are anagram or not?

  • Read or initialize two strings str1 and str2.
  • Find the length of both the strings.
  • Compare the length of the strings.
    1. If length is not equal, print strings are not an anagram.
    2. Else, do the following:
      1. Convert the string into a character array.
      2. Sort both the arrays by using the sort() method.
      3. After sorting, compare the strings by using the equals() method. Store the value in a Boolean variable (status) returned by the equals() method.
    3. Pass the variable in the if statement. If it returns true, the given strings are anagram. Else, not an anagram.

Let's implement the above steps in a Java program.

Java Anagram Program

There is various way to find anagram string but, in this section, we will focus on the following three ways.

  • Using Arrays Class
  • Using for Loop
  • Using StringBuilder Class

Using Arrays Class

In the following program, we have used to methods String.sort() and equals() method to check if the two strings are anagram or not.

AnagramExample1.java

Output:

HEART and EARTH are anagrams
TRIANGLE and INTEGRAL are anagrams
TOSS and SHOT are not anagrams

Using for Loop

AnagramExample2.java

Output:

true
true
false

Using StringBuilder Class

AnagramExample3.java

Output:

true
false