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.
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
How to check two strings are anagram or not?
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
In the following program, we have used to methods String.sort() and equals() method to check if the two strings are anagram or not.
HEART and EARTH are anagrams TRIANGLE and INTEGRAL are anagrams TOSS and SHOT are not anagrams
Using for Loop
true true false
Using StringBuilder Class