×

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java programme question is regularly asked.

Anagram

A phrase or a word that has been created by reversing the letters of that other phrase or a word is known as an anagram, or Anagrams are words or phrases created by rearranging the letters, according to the dictionary definition of the term.

If rearranging or mixing up the letters in two strings results in a meaningful term, then the corresponding strings are referred to as anagrams. In other words, if two strings include the same characters in a different order, we can say that they are anagrams. Remember that a letter only needs to be used once.

Let us have a look at some of the examples related to the anagram.

Example of Anagram

There are many anagrams of words, some of which include:

Moon starer = astronomer

Shrub = brush

Store scum = customers

Indicatory = dictionary

Dormitory = dirty room

Editor = redo it

Eleven plus two = twelve plus one

How can two strings be tested to see if they are anagrams?

  • Read or create the strings sr1 and sr2 from scratch.
  • Calculate the lengths of both strings.
  • Compare the strings lengths.
    1. Printing strings are not anagrams if the lengths are not identical.
    2. If not, take the next action.
      • The string should be changed into something like a character array.
      • Use the sort() method to sort both arrays.
      • Use the equals() method to compare the strings after sorting. The equals() method returns a Bool variable that should be used to store the value.
    3. In the if statement, pass the variable. The following strings are anagrams if the test returns true. Not an anagram is else.

Let's include the following activities into a Java programme.

Program for the Java Anagram

There are many ways to find an anagram string, however in this part we'll concentrate on the three methods listed below.

By Using the for Loop

Let the program file name be AnagramDemo.java

public class AnagramDemo  
{  
//function checks if the strings are anagram or not      
public static boolean theAnagram(String sr7, String sr9)   
{  
//comparing of the length      
if (sr7.length() != sr9.length())   
{  
// if the strings' lengths are not equal, returns incorrect.
return false;  
}  
// string to character array conversion
char[] characs = sr1.toCharArray();  
// loop cycles across the array.
for (char s : characs)   
{  
//finds the index      
int index = sr9.indexOf(s);  
if (index != -1)   
{  
//the substring() method returns a new string that is a substring of this string  
Sr9 = sr9.substring(0, index) + sr9.substring(index + 1, sr9.length());  
}   
else   
{  
return false;  
}  
}  
return sr9.isEmpty();  
}  
//It is the driver code  
public static void main(String args[])   
{    
//we are calling the function      
System.out.println(theAnagram("SHRUB", "BRUSH"));    
System.out.println(theAnagram("EAT", "TEA"));    
System.out.println(theAnagram("KAMAL", "MALAK"));   
}    
}    

Output:

What is anagram in Java

By Using the StringBuilder Class

Let the program file name be AnagramDemo2.java

public class AnagramDemo3  
{  
// determines whether the strings are anagrams or not.
public static boolean theAnagram(String sr7, String sr9)   
{  
// string to character array conversion
char[] charac = sr7.toCharArray();  
StringBuilder sa = new StringBuilder(sr9);  
// iterates through the character array in a loop.
for (char cr : charac)   
{  
// locates the char's index
int index = sa.indexOf("" + cr);  
if (index != -1)   
{  
// at the specified index, remove the character
sa.deleteCharAt(index);  
}   
else   
{  
return false;  
}  
}  
//It finds the length  
return sa.length() == 0 ? true : false;  
}  
//It is the driver code  
public static void main(String args[])   
{    
//It is calling the function      
System.out.println(isAnagram("TON", "NOT"));    
System.out.println(isAnagram("CAM", "MIC"));   
}    
}    

Output:

What is anagram in Java

By Using the Arrays Class

The equals() method and the String.sort() function are used in the programme below to determine whether or not the two texts are anagrams.

Let the program file name be AnagramDemo3.java

import java.util.Arrays;    
public class AnagramDemo3
{    
// function that determines whether or not the strings are anagrams
static void isAnagram(String sr7, String sr9)   
{    
// eliminates the white spaces in string 7
String sr7 = sr7.replaceAll("\\sr", "");    
//removes white spaces from string 2  
String sr9 = sr9.replaceAll("\\sr", "");    
boolean condition = true;    
// determines whether the lengths of the two strings are equal
if (sr7.length() != sr9.length())   
{    
// If the length of the strings differs, condition is false.
condition = false;    
}   
// executes if the string lengths are equal
else   
{    
// the string 7 is changed to lower case before being changed into a character array.
// arraySr7 saves the final string.
char[] arraySr7 = sr7.toLowerCase().toCharArray();    
// lowercases the number 9 in the string before turning it into a character array.
//fi arraySr9 contains the final string.
char[] arraySr9 = sr9.toLowerCase().toCharArray();    
// arraySr7's character set is sorted.
Arrays.sort(arraySr7);    
// arraySr9's character set is sorted.
Arrays.sort(arraySr9);    
//it will compar the strings  
status = Arrays.equals(arraySr7, arraySr9);    
}    
if (condition)   
{    
// if status is true, prints
System.out.println(sr7 + " and " + sr9 + " are the anagrams");    
}   
else   
{    
//prints if status returns false      
System.out.println(sr7 + " and " + sr9 + " are not the anagrams");    
}    
}    
//It is the driver code  
public static void main(String args[])   
{    
//we are calling function      
theAnagram("TEA", "ATE");    
theAnagram("BAT", "TAB");    
theAnagram("COOL", "LOOK");   
}    
}  

Output:

What is anagram in Java

Related Topics

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Find Unique Elements in Array Java

An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we...

6 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.