Java Program to Find Whether the given words are Anagram or Not

5:59 PM 32 Comments A+ a-

Anagrams as you might already know, are the words or phrase formed by rearranging the letters of another word. For example: angel and glean or stain and satin.

Well, my description of what the anagrams are ends here as this is not an English grammar tutorial site. What I am more interested in writing out a piece of code to which we can pass the words and can get know whether the words were anagram or not. Well, this is what the solo purpose of this tutorial at least. May be you'd asked such a question somewhere someday, may be in some interview or some coding test, so I just thought to post this here. 

So, how do we proceed? Java is such a powerful programming language that using the provided library methods, you might be able to do this in no more than couple of lines of code. Great if you can! But having faced enough number of interviews to assure you of that, the interviewer in most cases, are not that interested in knowing how good you're at memorizing the method and class names but how quickly your brain can find out a solution to the given problem and your approach. So, the chances are that the Java programming interview questions that you'd be asked would expect you to solve the problem without relying much upon the library methods.
Well, we'll do it both ways and we'll just take two words as the input to our method. You can easily extend the code to include more. (var-args might be of some help!)

Using the library methods

This just makes it ridiculously easy! We will be just reading the  given strings, sorting them using Arrays.sort() and then comparing the sorted strings. If the sorted strings are equal then the words were anagrams. Simple! Because the anagrams as already stated are the words formed by rearranging the words in hand. 

Without using the library methods

Without using the library methods also does not make it any less simpler. We can just first read the two strings, check for their same lengths, take one string character by character and search the other for each characters. And if all characters are found from one string are found in another then the two strings are anagrams because they were of same length. 

So, enough of the text, now the program!

Java program to check whether the two strings are anagram or not

import java.util.Arrays;
import java.util.Scanner;

public class AnagramDemo {

 // method to check for the anagrams using built-in methods
 public static boolean isAnagram(String str1, String str2) {

  char[] charArr1 = str1.toCharArray();
  char[] charArr2 = str2.toCharArray();

  // performing sorting of string
  Arrays.sort(charArr1);
  Arrays.sort(charArr2);

  return Arrays.equals(charArr1, charArr2);
 }

 // method to check for the anagrams without using library methods
 public static boolean isAnagramManual(String str1, String str2) {
  // if length itself not equal, return false.
  if (str1.length() != str2.length())
   return false;
  // else do the brainstorming!
  boolean anagram = true;

  for (int i = 0; i < str1.length(); i++) {
   if (str2.indexOf(str1.charAt(i)) == -1)
    anagram = false;
  }

  return anagram;
 }

 public static void main(String[] args) {

  System.out.println("First string");
  Scanner sc = new Scanner(System.in);
  String str1 = sc.nextLine();
  System.out.println("Second string");
  String str2 = sc.nextLine();
  System.out.println("Using library methods:-");
  if (isAnagram(str1, str2))
   System.out.println(str1 + " and " + str2 + " are anagrams!");
  else
   System.out.println(str1 + " and " + str2 + " are NOT anagrams!");

  System.out.println("WITHOUT USING LIBRARY METHODS");
  if (isAnagramManual(str1, str2))
   System.out.println("ANAGRAMS");
  else
   System.out.println("NOT ANAGRAMS");

 }

}


I hope that you find it useful. In case you find any mistakes or the better way of doing it, please write in comments.
In case you have any other Java related question or problem that you want me to write code for, please let me know in comments or mail me

Currently working at Symantec in Chennai. Previously worked as a Senior Software Engineer at IGATE. Loves to explore new things, loves to code and solve challenging problems with the help of it. Like any other normal person, loves to watch movies, listen to songs (specially when travelling, it is must), getting to know people, travelling and whatever makes me feel good!

32 comments

Write comments
Anonymous
AUTHOR
July 20, 2015 at 3:26 AM delete

thank you.

Reply
avatar
satish dixit
AUTHOR
November 17, 2015 at 2:36 PM delete

Nice post. I think you need to convert the strings to lowercase also.
For info refer this link , Write a program to check if two strings are anagrams or not.

Reply
avatar
Anonymous
AUTHOR
December 4, 2015 at 6:46 AM delete

I don't believe the isAnagramManual method works for words that are the same length and have all the same characters, but a different amount of each letter. For example, isAnagramManual("abcdd", "aabcd") returns true, but they are not actually anagrams.

Reply
avatar
Tenque
AUTHOR
February 29, 2016 at 1:18 PM delete

Thank you for sharing this article. It is much useful and i got some valid information with this site.

SAP MM Training in Chennai

Reply
avatar
Aamala Ahona
AUTHOR
March 1, 2016 at 2:28 PM delete

Everything is fine, am happy about your blog. Thanks admin for sharing the unique content, you have done a great job I appreciate your effort and I hope you will get more positive comments from the web users.

Regards,
Aamala

SEO Training in Chennai

Reply
avatar
kavimelly
AUTHOR
March 2, 2016 at 5:02 PM delete

The programming was very easily understand and more important coding are provided on this post and this is very valuable in my studies,all coding easily understand and develop more skills,thanks for sharing this post.
html5 training in chennai

Reply
avatar
raphael
AUTHOR
March 4, 2016 at 5:10 PM delete

Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.


digital marketing training Chennai

Reply
avatar
March 7, 2016 at 6:15 PM delete

Another great articles and very interesting to read,thanks for sharing that wonderful useful information,given programming coding was very excellent and easily observe all provided information.
ios training in chennai

Reply
avatar
henris
AUTHOR
March 21, 2016 at 11:47 AM delete

Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.

SQL DBA Training in Chennai

Reply
avatar
shalini
AUTHOR
March 22, 2016 at 1:16 PM delete

It is really good and informative thanks for sharing this information.it is really nice and useful too.


sharepoint developer training in chennai

Reply
avatar
Maani kamili
AUTHOR
June 17, 2016 at 6:03 PM delete

I am not sure the place you are getting your information, however good topic. I needs to spend some time studying more or understanding more. Thank you for wonderful information I was in search of this info for my mission.

Digital marketing company in Chennai

Reply
avatar
Dhiya L
AUTHOR
July 6, 2016 at 3:51 PM delete

Wow amazing i saw the article with execution models you had posted. It was such informative.By explaining this type we can identify the concepts easily. So thank you for this sharing.


Web Designing Training in Chennai Adyar

Reply
avatar
July 14, 2016 at 12:43 AM delete

This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

Love from Pprogramming

Reply
avatar
Praveen Kumar
AUTHOR
July 25, 2016 at 12:49 PM delete

The stuff provided was very useful for me in completing my project work. Thanks a lot SAP Simple Finance Training in India

Reply
avatar
Chinni Bocha
AUTHOR
August 1, 2016 at 6:28 PM delete

In my search for online SAP training, I bumped into www.call4training.com. Highly recommend this course to anyone struggling with understanding of SAP Basis.
SAP Hana training in hyderabad

Reply
avatar
Sathya G
AUTHOR
August 29, 2016 at 3:49 PM delete

This blog explains the details of most popular technological details. This helps to learn about what are all the different method is there. And the working methods all of that are explained here. Informative blog.
Digital Marketing Course in Chennai

Reply
avatar
Thanu Abi
AUTHOR
August 29, 2016 at 4:16 PM delete

This is really a great post. Thank you for taking time to provide us some of the useful and exclusive information with us. Keep on blogging!!

Seo Company in Chennai

Reply
avatar
Thamarai Ravi
AUTHOR
September 12, 2016 at 4:18 PM delete

nice blog too informative. looking and reading your points its so impressive. doing more blog like this. i really appreciated doing like this.
Digital Marketing Course in Chennai

Reply
avatar
Aasha
AUTHOR
February 1, 2017 at 3:08 PM delete

This blog explains the details about changing the ways of doing that business. That is understand well and doing some different process. Provides he best output of others. Thanks for this blog.
Web Development Company in India

Reply
avatar
March 15, 2017 at 11:44 AM delete

Core java is the essential for java with a view to being utilized in any java era without this nobody can bounce on any enhance java generation. in which as improve java is specialization in a few area, which includes networking, net, com or database dealing with.
So analyze extra approximately on line it courses on oracle fusion procurement training
from
oracle fusion procurement online training
oracle fusion procurement training

Reply
avatar
ERP
AUTHOR
March 21, 2017 at 12:43 PM delete


wonderful information, I had come to know about your blog from my friend nandu , hyderaba.
i have read atleast 7 posts of yours by now, and let me tell you, your website gives the
best and the most interesting information. This is just the kind of information that i had
been looking for, i'm already your rss reader now and i would regularly watch out for the new posts.


Oracle Fusion HCM Training

Reply
avatar
April 10, 2017 at 10:56 AM delete

Hi,
This is a good post.
Thanks for sharing such a nice post.
oracle fusion SCM online training

Reply
avatar
Calfre India
AUTHOR
April 21, 2017 at 5:29 PM delete

This article creates a new hope and inspiration with in me. Thanks for sharing article like this. The way you have stated everything above is quite awesome. Keep blogging like this. Thanks.



Oracle fusion Financials Online Training in Ameerpet

Oracle Fusion Financials Training in Ameerpet

Reply
avatar
Riya R
AUTHOR
April 25, 2017 at 2:50 PM delete

informative blog thanks for providing such a great information.
SharePoint jobs in Hyderabad
SharePoint jobs in Chennai

Reply
avatar
Vignesh PV
AUTHOR
April 26, 2017 at 7:40 PM delete

your information is really awesome as well as it is very excellent and i got more interesting information from your blog.

iOS App Development Company

Reply
avatar
Smith
AUTHOR
May 5, 2017 at 10:30 AM delete

An important building block of SEO is to develop your website which can be easily understandable for both Online Visitors (most important) and search engine robots. In the current digital age, seo is important for your online success means to generate leads.

SEO Services in IndiaSEO Company in India SEO Company in India SEO Services in India

SEO Company in India SEO Services in India

Reply
avatar
May 15, 2017 at 6:10 PM delete

Superb blog. Thank you for providing excellent information in which the code allowed me to understand the coding of selenium. Continue to publish regularly

Reply
avatar