How to Check if Two Java Strings are Anagrams

How to Check if Two Java Strings are Anagrams

5 mins read989 Views Comment
Updated on Feb 28, 2023 21:17 IST

In this article, we will learn different methods to check whether two java strings are anagram or not.

2023_02_MicrosoftTeams-image-199.jpg

Anagram is a word or a phrase that is made by arranging the letters of another word or phrase in a different order. In this article, we will discuss different methods to check whether given two java strings are anagram or not.

So, without further delay let’s learn these methods.

What is Anagram?

When all the characters of the two Strings have the same frequency, then we say that the two Strings are Anagrams. For example:

2023_02_image-191.jpg

Here in the above examples, we observe that the two strings have the same number of characters, and the frequency of each character in both strings is also the same. Hence we say that the two strings are anagrams of each other.

Must Read: Strings in Java

Must Read: How to Reverse a String in Java

Methods to check if two strings are anagrams

sort both strings and compare

In the below program, we take String inputs from the user using the nextLine() method of the Scanner class. The characters of these strings are converted into lowercase using the toLowerCase() method of the String class. Then these strings are converted into character arrays by using the toCharArray() method of the String class. We make a method isAnagram(), which accepts two character arrays as arguments. In this method, first, we check if the length of both arrays is not the same, then we return false otherwise, we go further in the program. Loop for the length of the string to check for each index of the character array; if the character in both the arrays is not equal, then return false. If all the false conditions are not executed, then the method returns true, which means strings are Anagrams.

Code:

 
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static boolean isAnagram(char[] first,char[] second) {
//checking length of first string is not equal to second string then return false
if(first.length!=second.length) {
return false;
}
//check character in first string is not equal to character in second string then return false
for(int i=0;i<first.length;i++) {
if(first[i]!=second[i]) {
return false;
}
}
// return true when all characters in both strings are same
return true;
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter first String:");
//input first string
String first_string=sc.nextLine();
System.out.println("Enter second String:");
//input second string
String second_string=sc.nextLine();
//convert first string into lower case
first_string=first_string.toLowerCase();
//convert second string into lower case
second_string=second_string.toLowerCase();
//convert first string into char array
char[] first_array=first_string.toCharArray();
//convert second string into char array
char[] second_array=second_string.toCharArray();
//sort first array
Arrays.sort(first_array);
//sort second array
Arrays.sort(second_array);
//calling isAnagram boolean function
if(isAnagram(first_array,second_array)) {
System.out.println("Two Strings are Anagrams");
}else {
System.out.println("Two Strings are not Anagrams");
}
}
}
Copy code

Output:

2023_02_image-190.jpg

By using two frequency array

In the below program, we take String inputs from the user using the nextLine() method of the Scanner class. The characters of these strings are converted into lowercase using the toLowerCase() method of the String class. Then these strings are converted into character arrays by using the toCharArray() method of the String class. We make a method isAnagram(), which accepts two character arrays as arguments. In this method, first, we check if the length of both arrays is not the same, then we return false otherwise, we go further in the program. We make two frequency arrays of type integer. Frequency array count1 stores the frequency of each character in the first character array, and frequency array count2 stores the frequency of each character in the second character array. Then loop for 256 times to check whether the frequency count of characters in both frequency arrays is not the same, then return false. If all false condition is not executed, then the method returns true, which means strings are Anagrams.

Must Check: Implementing Array in Java

Code:

 
import java.util.Scanner;
public class Main{
public static boolean isAnagram(char[] first,char[] second) {
//checking length of first string is not equal to second string then return false
if(first.length!=second.length) {
return false;
}
int[] count1=new int[256];
int[] count2=new int[256];
for(char c:first) {
int v=(int)c;
count1[v]++;
}
for(char c:second) {
int v=(int)c;
count2[v]++;
}
for(int i=0;i<256;i++) {
if(count1[i]!=count2[i]) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter first String:");
//input first string
String first_string=sc.nextLine();
System.out.println("Enter second String:");
//input second string
String second_string=sc.nextLine();
//convert first string into lower case
first_string=first_string.toLowerCase();
//convert second string into lower case
second_string=second_string.toLowerCase();
//convert first string into char array
char[] first_array=first_string.toCharArray();
//convert second string into char array
char[] second_array=second_string.toCharArray();
//calling isAnagram boolean function
if(isAnagram(first_array,second_array)) {
System.out.println("Two Strings are Anagrams");
}else {
System.out.println("Two Strings are not Anagrams");
}
}
}
Copy code

Output

2023_02_image-192.jpg

Must Read: What is Java?

Must Check: Java Online Courses and Certification

By using one frequency array

In the below program, we apply the same logic as we have done in the above program, but the change is that instead of using two frequency arrays, we use one frequency array. The main logic of the program is that, in the frequency array count, first increment the count of the first character array and then decrement the count of the character of the second character array. Please observe the code for better understanding.

Code:

 
import java.util.Scanner;
public class Main{
public static boolean isAnagram(char[] first,char[] second) {
//checking length of first string is not equal to second string then return false
if(first.length!=second.length) {
return false;
}
//Frequency array of size 256 and
int[] count=new int[256];
for(int i=0;i<first.length;i++) {
//increment of chracter count in frequency array count
count[first[i]]++;
//decrement of same character count in frequency array count
count[second[i]]--;
}
//Loop for 256 times to check the frequency count of character in frequency array
//If frequency count is not equal to zero then return false
for(int i=0;i<256;i++) {
if(count[i]!=0) {
return false;
}
}
// return true when all characters in both strings are same
return true;
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter first String:");
//input first string
String first_string=sc.nextLine();
System.out.println("Enter second String:");
//input second string
String second_string=sc.nextLine();
//convert first string into lower case
first_string=first_string.toLowerCase();
//convert second string into lower case
second_string=second_string.toLowerCase();
//convert first string into char array
char[] first_array=first_string.toCharArray();
//convert second string into char array
char[] second_array=second_string.toCharArray();
//calling isAnagram boolean function
if(isAnagram(first_array,second_array)) {
System.out.println("Two Strings are Anagrams");
}else {
System.out.println("Two Strings are not Anagrams");
}
}
}
Copy code

Output

2023_02_image-193.jpg

By using HashMap

In the below program, we use HashMap with Character as key and Integer as value. First, we loop for the length of the character array first and check if the key is present, then increment the count of characters, and if not present in the map, then put 1 for the count of characters. Second, we loop for the length of the character array second and check if the key is present, then decrement the count of the character and return false if the key is not present. If all false conditions are not executed, then the isAnagram() method returns true, which means strings are Anagrams.

import java.util.*;
public class Main{
public static boolean isAnagram(char[] first,char[] second) {
//checking length of first string is not equal to second string then return false
if(first.length!=second.length) {
return false;
}
//creating HashMap with Character as key and Integer as value
HashMap<Character,Integer> map=new HashMap<>();
//Loop in char array first
//put value 1 for character not present in hashmap
//Increment value if character is present
for(int i=0;i<first.length;i++) {
if(map.containsKey(first[i])) {
map.put(first[i], map.get(first[i])+1);
}else {
map.put(first[i], 1);
}
}
//Loop in char array second
//return false if character is not present in hashmap
//Decrement value if character is present
for(int i=0;i<second.length;i++) {
if(map.containsKey(second[i])){
map.put(second[i], map.get(second[i])-1);
}else {
return false;
}
}
//extract all keys of map
Set<Character> keys=map.keySet();
// for each key check value
//return false if value is not equal to 0
for(Character key:keys) {
if(map.get(key)!=0) {
return false;
}
}
// return true when all characters in both strings are same
return true;
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter first String:");
//input first string
String first_string=sc.nextLine();
System.out.println("Enter second String:");
//input second string
String second_string=sc.nextLine();
//convert first string into lower case
first_string=first_string.toLowerCase();
//convert second string into lower case
second_string=second_string.toLowerCase();
//convert first string into char array
char[] first_array=first_string.toCharArray();
//convert second string into char array
char[] second_array=second_string.toCharArray();
//calling isAnagram boolean function
if(isAnagram(first_array,second_array)) {
System.out.println("Two Strings are Anagrams");
}else {
System.out.println("Two Strings are not Anagrams");
}
}
}
Copy code

Output

2023_02_image-194.jpg

Conclusion

In this article, we have discussed different methods to check whether two strings in java are anagram or not.

Hope you will like the article.

Keep Learning!!

Keep Sharing!!

Contributed By: Shubham Kumar

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio