≡ Menu

Java Practice Assignment #4 – The Anagram

Alright ladies and gentlemen, this week’s assignment is in. But before we get into it:

Click Here to download my particular solution for Assignment 3.

There will be many ways to solve this assignment, and I’m not saying that my solution is the best solution, but if you were having trouble getting your assignment to work, then mine might help you out. If you feel like you’ve got a better solution feel free to shoot it over to me via email at info@howtoprogramwithjava.com. I’ll post it here as another solution so that everyone may benefit :)

Assignment #4 – The Anagram

Before you read through and download this assignment, I’d like to ask you for a favour. Back in October of 2012 I decided to quit my 9-5 day job and take a run at doing what it is I love to do full-time: creating fun and educational tutorials like this one. So since this has now become my livelihood, it would really mean the world to me if you took a few seconds to share this content with the world. The more people I have sharing this stuff, the more chance I’ll have at being able to continue doing what it is I love, and that’s helping YOU guys out. So if you have a moment, please click one of the sharing options to the left of this, and if you do I humbly thank you.

Click Here to download the assignment files for Java practice assignment #4. Video instructions on how to install these files into your IDE can be seen at the bottom of this post.

This is one of my favourite types of assignments, it’s an algorithm assignment. This type of assignment is design to test your skills at creating an algorithm that will solve the presented problem. Remember that there are MANY ways to solve this problem, your goal should be to create code that is as efficient as possible. Your task for Java practice assignment #4 is to code an anagram solver. First of all, we’ll define the term “anagram” for this assignment:

An anagram is considered to be a pair of words that are made up of the exact same letters. Think of it like taking one word, then just scrambling the letters around until you can spell another word. For the purposes of this assignment we’ll only be dealing with single word anagrams, as there are certainly anagrams that can be formed by multiple words (but let’s not worry about those ones). Here are some examples of valid anagrams:

care -> race
tool -> loot
cloud -> could

An example of words that a NOT anagrams:

tool -> toll (doesn’t have the exact same number of letters)
cloud -> clouds (one word is longer than the other)

So, your task will be to create a method that will return true or false (anagram or NOT an anagram) based on the two Strings that will be passed in. Be sure to follow the instructions included in the assignment files!

Installation Instructions

Here’s a quick video that will explain how to install this assignment:

Dude... Seriously... Take our FREE Java Video Tutorials Course...
You'll receive a new Java Video Tutorial lecture straight to your inbox, twice a week.  How cool is that?

{ 3 comments… add one }

  • Bernd January 23, 2013, 4:25 am

    Since the assigbnement is a while ago, I think I can show my solution…
    My personal challenge was to get the solution into one line. Well, I _almost_ succeeded.

    My algorithm is: sort the uppercase or lowercase strings and compare them. If they match, they are anagrams.
    Unfortunatelly there is no funtion/metod in Java which returns a sorted String or Array (all sorting methods sort in-place and return nothing, i.e. they are void).
    So I had to provide my own function for this task.
    Today I stumbled upon a very critical topic concerning toLowerCase, toUpperCase: Locale. There are some very special characters in german (sharp s=ß, which becomes SS in uppercase) and turkish undotted lowercase i and dotted uppercase I). Please follow the links in the source to learn more.

    String.compareToIgnoreCase(str2) would handle these cases just fine, but for this anagram assigment I had to upperCase() the String first and then sort it.

    I have added two test cases which deal with these special cases:

      public void should_treat_turkish ()
        boolean anAnagram = sut.isAnAnagram("Biılly", "BİILLY");
        assertThat(anAnagram, is(true));
      public void should_treat_non_turkish ()
        boolean anAnagram = sut.isAnAnagram("Billy", "BILLY");
        assertThat(anAnagram, is(true));

    The code isAnagram is hard to read according to my one-line goal. This is not an example of clear, readable code, but it works.

          public class AnagramSolverImpl implements AnagramSolver {
    	public boolean isAnAnagram(String word1, String word2) {
    		return !(word1 == null || word2 == null || !sortUcString(word1).equals(sortUcString(word2)));
    	private String sortUcString(String inStr) {
    		// assertion: inStr is not null
    		// Beware of Turkish locale (dotted, undotted i)
    		//  http://mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug
    		//  http://java.dzone.com/articles/policemans-horror-default
    		// And german (all locales) ß toUpperCase: SS but not vice-versa!
    		Locale loc = Locale.ENGLISH;
    		// Contains undotted small i or dotted capital I?
    		// => Must be turkish.
    		if (inStr.contains("ı") || inStr.contains("İ")) {
    			loc = Locale.forLanguageTag("tr");
    		char[] wordArr = inStr.toUpperCase(loc).toCharArray();
    		return new String(wordArr);
  • Ashish July 28, 2014, 7:10 am

    An anagram is a type of word, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once.

    For example: orchestra can be rearranged into carthorse or cat can be rearranged into act.

    We can find out the anagram strings using below algorithm:

    public static boolean isAnagram(String str1, String str2) {
    if (str1 == null || str2 == null) {
    return false;
    } else if (str1.length() != str2.length()) {
    return false;

    Map map = new HashMap();

    for (int i = 0; i < str1.length(); i++) {
    char characters = str1.charAt(i);
    int charInStr1 = map.containsKey(characters) ? map.get(characters) : 0;
    map.put(characters, ++charInStr1);
    char charFromStr2 = str2.charAt(i);
    int charsInRight = map.containsKey(charFromStr2) ? map.get(charFromStr2) : 0;
    map.put(charFromStr2, –charsInRight);

    for (int occurrences : map.values()) {
    if (occurrences != 0) {
    return false;
    return true;

    I found below useful links for more information

    Write program to find if Strings are anagram

  • Pramod February 20, 2015, 2:14 am

    Very nice assignment….

Leave a Comment