Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconJava Program to Check If Two Strings are Anagram | Anagram Program

Java Program to Check If Two Strings are Anagram | Anagram Program

Last updated:
23rd Jul, 2021
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
Java Program to Check If Two Strings are Anagram | Anagram Program

Less known facts about Java

Being one of the most durable programming languages, Java is used across the globe because of its robust and flexible features. The stability and versatility of Java have made it one of the most sought-after programming languages. However, there are several less known facts about this secure programming language. Let’s get to know a few of them.

  • Oak is the original name of Java.
  • You can earn a lot while learning this programming language.
  • Java is the second most populous programming language in the world, the first one being the C.
  • About 3 billion devices across the world are working on Java.
  • Java is a case sensitive programming language. i.e., “Final” and “final” are not the same in Java code. Read more on why java is so popular with the developers.

Check out our free courses to get an edge over the competition.

An Overview of Anagram

If a string is transformed into another string by rearranging its characters, then the two strings are said to be the anagrams of each other. However, the number of characters in the initial string and the string obtained should be the same. To understand the concept of an anagram in a better manner, let us consider two strings, ‘god’ and ‘dog’.

The strings ‘god’ and ‘dog’ are anagrams of each other because the former string can be rearranged to get the latter one just by interchanging the positions of characters ‘d’ and ‘g’. For any two input strings, the frequency of each character is calculated to check whether the strings are anagrams of each other or not. So, an anagram of a string can be defined as any other string that has the same characters with the same frequency as in the input string in any sequence.

Ads of upGrad blog

Check out upGrad’s Advanced Certification in DevOps

Algorithm for Anagram Program in Java

Step 1: Define the two input strings.

Step 2: The length of each string is determined. Input strings are not anagrams of each other if they have different string lengths.

Step 3: If the strings have the same length, the string characters are converted to lower case letters to ensure the comparison easier.

Step 4: The string characters are either sorted by inbuilt functions or converted into a character array and then sorted. 

Step 5: The sorted array of characters are checked for equality. 

In-Demand Software Development Skills

Check out upGrad’s Java Bootcamp.

Implementation of Anagram program in Java

There are several solutions to implement a code to find whether two strings are anagrams or not. For each solution discussed in the subsequent sections, Step 2 of the algorithm described above forms the basis and facilitates early exit if the string lengths do not match. In the subsequent sections, let’s understand more about the different types of writing a code for anagram logic.

Sorting Approach

The characters of each input string can be sorted to obtain two normalized character arrays. If the normalized arrays of both the input strings are the same, then the strings are considered to be anagrams of each other and vice versa. 

The understanding and implementation of this code are easier. The time complexity of the above solution is O(n log n) and additional space is required to store character arrays of the input strings.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Explore our Popular Software Engineering Courses

Counting Approach to Implementing Anagram Logic

In this approach, the number of existences of each character in the two input strings is measured. If the frequency of each character in both the strings is identical, the strings are anagrams of each other. 

Let us build a single histogram to save some memory. In the first string, the counts of each character are incremented, whereas the counts are decremented for the second one. If the ultimate result balances everything to zero, then the strings are anagrams.  

This solution executes faster than the previous solution and its time complexity is O(n). However, additional space is required to count the characters. This solution is practically effective only for strings with a smaller character range. Another fact about this solution is it uses a limited number of inbuilt Java functions and thus increases the length of the code. 

Checkout: Java Project Ideas & Topics

Determine Anagrams by checking with MultiSet

The use of MultiSet, a collection that aids order-independent comparison with identical elements, simplifies the process of counting and comparing in this solution. 

Each input string is initially converted into a MultiSet of characters and then checked for parity. 

Ads of upGrad blog

The time complexity of this solution is O(n). It is similar to the counting approach to determine anagrams. However, it can work efficiently for strings of greater lengths. Also, coding involves a greater number of Java Library functions.

Explore Our Software Development Free Courses

Letter Based Approach to determine Anagrams

All the solutions discussed so far consider the punctuation characters also as a part of the string. Moreover, those solutions are case sensitive. The letter-based approach implements a code to check the input strings based on the linguistic definition of anagrams. In this approach, the white spaces and punctuations are not considered as a part of the input string.

The initial step while implementing a letter-based solution is the elimination of unwanted characters and conversion of all valid characters into lowercase letters. After this step, any of the above-discussed implementations can be used to check whether the strings are anagrams or not. 

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development – Specialisation in Full Stack Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.



Blog Author
Meet Sriram, an SEO executive and blog content marketing whiz. He has a knack for crafting compelling content that not only engages readers but also boosts website traffic and conversions. When he's not busy optimizing websites or brainstorming blog ideas, you can find him lost in fictional books that transport him to magical worlds full of dragons, wizards, and aliens.

Frequently Asked Questions (FAQs)

1Is Java a beginner-friendly language?

While it may not be as intuitive as some other languages such as, say, Python, Java is still a high-level language and that makes it suitable for beginners. Due to its wide-ranging applications and immense popularity, there is an abundance of useful resources available, from textbooks and tutorials to worksheets and pop quizzes. The learning curve is not particularly steep – if you put in 3 hours every day, you can develop a solid understanding of Java fundamentals within 2-3 weeks. If you can keep up that dedicated practice for a year or two, you can master the language. You will then have a multitude of career options at your disposal.

2What are some standard practice questions beginners must try while learning Java?

No matter how many textbooks of theory one reads, one cannot truly learn to code without actual hands-on practice. Trying multiple approaches, dealing with frustrating errors, dry running, and debugging – these routines are like a rite of passage for all novice coders. There are many easy programs that beginners can attempt while learning the fundamentals of Java. These programs involve simple arithmetic, basic loops, and conditional statements. Some of them include the leap year calculator, prime number printer, vowel/consonant detector, complex number adder, factorial calculator, LCM and GCD identifier, and the simple interest and compound interest compiler, to name a few.

3What are the benefits of learning Java?

Java is extremely popular, because of its versatility. You can code a program once in Java and then deploy it on a variety of platforms. There are many high-paying job opportunities in Java, especially in Android application development. Java is an object-oriented language, which means it has features such as abstraction, encapsulation, inheritance, and polymorphism. It is flexible, system modular, and extensible. Java is also open source, so it is free to use. There are many powerful IDEs and development tools such as IntelliJ and Netbeans that have made coding in Java pleasant and convenient.