Table of contents
1.
Introduction
2.
What is an anagram program in Java?
2.1.
Anagrams
3.
Anagram Program in Java Using Sorting
3.1.
Algorithm:
3.2.
Program:
3.3.
Java
3.3.1.
Output:
4.
Anagram Program in Java Using Hashmap
4.1.
Algorithm:
4.2.
Program:
4.3.
Java
4.3.1.
Output:
5.
Anagram Program in Java Using Count Characters
5.1.
Algorithm:
5.2.
Java
6.
Anagram Program in Java Using Count Characters with One Array for English Letters
6.1.
Algorithm:
6.2.
Java
7.
Java Arrays
8.
Java Strings
9.
Frequently Asked Questions
9.1.
In Java, how do you create an array?
9.2.
In Java, why is it that strings are immutable?
9.3.
What data type is string Java?
9.4.
What are the characteristics of the Java programming language?
10.
Conclusion
Last Updated: Nov 7, 2024
Easy

Java Program to Check if Two Strings are Anagrams

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Anagrams are a fun and interesting concept in programming and linguistics. Two strings are considered anagrams if they contain the exact same characters in the same frequencies, just arranged in a different order. For instance, the words "listen" and "silent" are anagrams of each other, as they both contain the characters 'l', 'i', 's', 't', 'e', and 'n' in equal quantities.

In this blog post, we’ll explore how to create a Java program that checks if two strings are anagrams.

Java Program to Check if Two Strings are Anagrams

What is an anagram program in Java?

An anagram program in Java is designed to check if two given strings are "anagrams" of each other. In simple terms, two strings are considered anagrams if they contain the exact same characters in the same frequencies, but in a different order. For example, "listen" and "silent" are anagrams because both strings contain the characters 'l', 'i', 's', 't', 'e', and 'n' with equal frequency.

Anagrams

An anagram of a string is a distinct string made up of the same characters in a different order. "arc" and "car" are anagrams of each other.

(Image showing different words that are anagrams to each other)

Also Read About, Multithreading in java, and Duck Number in Java.

Anagram Program in Java Using Sorting

In the first method to check whether two strings are anagram are not, we will use sorting. We have to sort both the strings and compare both sorted strings. If they are found to be equal, the strings are anagram; otherwise, not.

Algorithm:

  1. START
  2. Take USER INPUT first_string and second_string.
  3. CONVERT first_string, second_string to lowercase
  4. PRINT "Not Anagram" if the lengths of first_string and second_string are not equal; otherwise, proceed to Step 5.
  5. CONVERT first_string, second_string to character arrays
  6. SORT the arrays
  7. COMPARE the arrays and print "Strings are Anagram" if they are equal; else, print "Strings are not Anagram."
  8. END

Program:

  • Java

Java

/*Program to check if two strings are anagram*/
import java.util.*;
class CheckAnagram
{
   public static void main(String args[])
   {
       //taking input from user
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter the first string");
       String s1=sc.nextLine();
       System.out.println("Enter the second string");
       String s2=sc.nextLine();
       //converting string to lower case
       s1 = s1.toLowerCase();
       s2 = s2.toLowerCase();
       //converting string to character array
       char[] ch1=s1.toCharArray();
       char[] ch2=s2.toCharArray();
       //sorting the character array
       Arrays.sort(ch1);
       Arrays.sort(ch2);
       //display if strings are anagram or not
       if(Arrays.equals(ch1,ch2))
       {
           System.out.println("The strings are anagram");
       }
       else
       {
           System.out.println("The strings are not anagram");
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

Output:

We took the user’s inputs in the Java program above. Then we converted the input strings to lower case. Again, we converted strings to character arrays. Now we sort the array and check if both sorted arrays are equal. If both the sorted arrays are equal, we display the message “The strings are anagram” otherwise display “The strings are not an anagram.”

Time Complexity: O(N log N)

Anagram Program in Java Using Hashmap

We learnt to check if two strings are anagrams using sorting in the above program. Now, we will learn to code the same using the Hashmap method in Java. Let’s get started with the hashmap method to check whether both the strings are anagrams or not.

Algorithm:

  1. START
  2. Take User INPUT first_string and second_string.
  3. CONVERT first_string, second_string to lowercase
  4. INITIALISE count variable to 0.
  5. CREATE a HashMap object with the key character and the value of character occurrences.
  6. If the character appears in the first string, the character count is INCREASED by one.
  7. If the character appears in the second string, the character count is DECREASED by one.
  8. ITERATE through HashMap, checking the count of each character on the map.
  9. DISPLAY “Strings are anagram” if the count is 0, otherwise “Strings are not an anagram.”
  10. END

Program:

  • Java

Java

/*Program to check two strings anagram using hashmap*/
import java.util.*;
class CheckAnagram
{
   public static void main(String args[])
   {
       //taking input from user
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter the first string");
       String s1=sc.nextLine();
       System.out.println("Enter the second string");
       String s2=sc.nextLine();
       //converting string to lower case
       s1 = s1.toLowerCase();
       s2 = s2.toLowerCase();
       //initialising count to 0
       int count=0;
       //creating hashmap
       HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
       for(int i=0;i<s1.length();i++)
       {
           if(hm.containsKey(s1.charAt(i)))
           {
               hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
           }
           else
           {
               hm.put(s1.charAt(i),1);
           }
       }
       for(int i=0;i<s2.length();i++)
       {
           if(hm.containsKey(s2.charAt(i)))
           {
               hm.put(s2.charAt(i),hm.get(s2.charAt(i))-1);
           }
           else
           {
               hm.put(s2.charAt(i),-1);
           }
       }
       for(Map.Entry<Character,Integer> m:hm.entrySet())
       {
           if(m.getValue()!=0)
           {
               count++;
           }
       }
       //print the result
       if(count==0)
       {
           System.out.println("The two strings are anagram");
       }
       else
       {
           System.out.println("The two strings are not anagram");
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

Output:

In the hashmap method, we have incremented the value of the key for the first array, decrement the value for the second array, and then validated the map size. We have taken two strings as input from the user and checked if they are anagrams or not.

Time-Complexity: O(N)

Try it by yourself on java online compiler.

Also check out Addition of Two Numbers in Java here.

Must Read Array of Objects in Java

Anagram Program in Java Using Count Characters

In this approach, we check if two strings are anagrams by counting the occurrences of each character in both strings and comparing those counts. Here, we use an array of fixed size (typically 256 for ASCII characters or 26 for lowercase English letters) to track the frequency of each character.

Algorithm:

  1. Check Length: If the lengths of the two strings are not equal, return false as they can't be anagrams.
  2. Initialize Count Array: Create an integer array of size 256 (to cover all ASCII characters) and initialize all elements to 0.
  3. Count Characters: For each character in the first string, increment the count in the array. For each character in the second string, decrement the count.
  4. Check Count Array: If all elements in the count array are zero, the strings are anagrams. If any element is non-zero, the strings are not anagrams.
  • Java

Java

public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
// Step 1: Check if lengths are equal
if (str1.length() != str2.length()) {
return false;
}

// Step 2: Initialize the count array for ASCII characters
int[] count = new int[256];

// Step 3: Increment for str1 and decrement for str2
for (int i = 0; i < str1.length(); i++) {
count[str1.charAt(i)]++;
count[str2.charAt(i)]--;
}

// Step 4: Check if all counts are zero
for (int i = 0; i < 256; i++) {
if (count[i] != 0) {
return false;
}
}

return true;
}

public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";

if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

listen and silent are anagrams.

Explanation:

  • Count Array: We used an array of size 256 (covering ASCII characters), where each index represents a character, and the value at that index represents the character’s frequency.
  • Increment/Decrement: By incrementing the count for each character in the first string and decrementing it for each character in the second string, we end up with a zero count for each character if the strings are anagrams.

Anagram Program in Java Using Count Characters with One Array for English Letters

This approach is similar to the above but optimized for lowercase English letters only (a–z). We use an array of size 26 to track the frequency of each letter, reducing memory usage compared to an array of size 256.

Algorithm:

  1. Check Length: If the lengths of the two strings are not equal, return false.
  2. Initialize Count Array: Create an integer array of size 26 for the letters 'a' to 'z' and initialize all elements to 0.
  3. Count Characters: For each character in the first string, increment the count at the corresponding index (character - 'a'). For each character in the second string, decrement the count.
  4. Check Count Array: If all elements in the count array are zero, the strings are anagrams. If any element is non-zero, the strings are not anagrams.
  • Java

Java

public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
// Step 1: Check if lengths are equal
if (str1.length() != str2.length()) {
return false;
}

// Step 2: Initialize count array for 26 lowercase English letters
int[] count = new int[26];

// Step 3: Update count array
for (int i = 0; i < str1.length(); i++) {
count[str1.charAt(i) - 'a']++;
count[str2.charAt(i) - 'a']--;
}

// Step 4: Check if all counts are zero
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
return false;
}
}

return true;
}

public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";

if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams.");
}
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

listen and silent are anagrams.

Explanation:

  • One Array (26 elements): The array tracks the frequency of each lowercase letter from 'a' to 'z', with each index corresponding to a letter.
  • Memory Efficient: This method is more efficient in terms of memory since it only considers lowercase letters, assuming the input contains no uppercase letters or special characters.

Java Arrays

We can define an array as a collection of data of similar types. Furthermore, an array's items are kept in a single memory address. It's a data structure where we save similar items. We can only store a fixed number of elements in a Java array. You must decide on the array's size before you begin. You can't change the size of an array once you create an array.

Each memory location in the Java array is assigned a number. We use the term ‘array index’ for this number. We can also use this index number to initialise arrays in Java. The compiler assigns the 0th index to the array's first element, the 1st index to the array's second member, etc. We can create single-dimensional and multidimensional arrays in Java, just like in C/C++.

Example of array declaration in Java:

int array[]=new int[10];

Java Strings

In Java, a string is a collection of char values represented as an object. An array of characters functions similarly to a Java string. Java Strings are a great way to store data in your application. We can use them to store anything from simple text to complex objects. Java String is immutable, which means once we create a string, we can not change it. This property makes them ideal for storing information that needs to remain constant throughout the program's life.

The String class in Java has numerous methods for manipulating strings: concat(), equals(), split(), replace(), substring(), intern(), etc.

Frequently Asked Questions

In Java, how do you create an array?

To begin, create a variable with the array type you want. Second, allocate memory for the array with new and assign it to the array variable. As a result, dynamic allocation occurs in the case of Java arrays.
Syntax:
→ type variable-name[];
→ type[] variable-name;

In Java, why is it that strings are immutable?

Because of security, synchronisation and concurrency, caching, and class loading, the String in Java is immutable. The purpose of declaring string final is to break its immutability and prevent others from extending it. The String pool caches the String objects, which makes the String immutable.

What data type is string Java?

A String in Java is a non-primitive data type. We can use methods on the String object to execute various string operations.

What are the characteristics of the Java programming language?

The Java Programming Language has the following features:
→ Portability
→ Object-Oriented programming language
→ Platform independent
→ Robustness
→ Dynamic
→ Distributed
→ Multithreaded

Conclusion

In this post, we learned:

  • the basics of Java Strings
  • Java Arrays and what an anagram is.
  • To create a Java program to check if two strings are anagram or not. 
  • We took two input strings from the user and stored them in two different strings. 
  • We converted them to lower cases and sorted them. If they are equal, both strings are anagram; otherwise, they are not.

We hope you've better understood basic java programming and the program to check if two given strings are anagrams. If you're interested in finding out more, see our articles on ‘print characters in a string’ and ‘selenium interview questions.’ Please upvote our blog so that other ninjas can benefit from it.

Also check out - String Interview Questions In Java

Recommended problems -

 

Visit our practice platform Code360 to get started. Here you can practice top problems, attempt mock tests, read interview experiences, and more.!

Happy Reading!

Live masterclass