Java Coding Week #1

Robert Torok September 27, 2018
Java Coding Week #1

Going forward I would like to present three coding challenges in Java with their solutions every week. This series will cover tasks that are often coming up in interviews as well. In case you happen to be a beginner it’s definitely worth checking back occasionally since practicing these exercises will improve your programming skills. Not to mention the fact that you can easily encounter one of these questions at the whiteboard when being interviewed.

Reverse and Display a String

Okay, let’s get started! The first, warm-up question is as follows:

Write a function that reverses and displays a string on the standard output!

Here’s our first solution:

public void reverseString(String word) {
    if (word == null || word.isEmpty()) {
        return;
    }

    StringBuilder sb = new StringBuilder();
    for (int i = word.length() - 1; i >= 0; i--) {
        sb.append(word.charAt(i));
    }

    System.out.println(sb.toString());
}
jshell> reverseString("Hello World!")
!dlroW olleH

jshell>

How does this code work? First, we create a StringBuilder object where we store the result. Then, starting from the very last position in the string, character by character, we go back to the first position in the string and add each character to our StringBuilder instance pointed by variable sb . Now we have a StringBuilder object containing the characters in the reverse order – the toString() method will take care of converting it to a String instance that finally we can display on the standard input.

Even though it’s a very simple task, there might be at least two typical questions to beginner developers:

Why do you use StringBuilder? You could also create a new String and concatenate the characters to it!

Answer: Yes, but String is an immutable type – you can’t modify an existing String object. In other words, every time when you concatenate it, you actually create a brand new String instance. Thus, concatenating String types turns to be an expensive operation and we’d like to avoid it. However, the compiler may be able to recognize the concatenations under the hood and convert them to StringBuilder objects. This combines the best of both worlds: There’s no performance penalty for using concatenations and you can also have a clear, verbose-less syntax.

Why do you start the loop from word.length() - 1? Why not word.length()?

Answer: Because, as in many other programming languages, the indexing of the string starts from zero. So the position length() - 1 actually refers to the last element.

And here’s a bonus, one-liner solution to this problem:

public void reverseStringAlternative(String word) {
    if (word == null || word.isEmpty()) {
        return;
    }

    System.out.println(new StringBuilder(word).reverse().toString());
}
jshell> reverseStringAlternative("Alternative version!")
!noisrev evitanretlA

jshell>

The StringBuilder class, unlike the String class, happens to have a reverse() method that does the most of the work for us.

Count Without Loops

The second excersie for today:

Write a function that prints the odd numbers from 0 to 10 (inclusive) without using loops!

That is, no for, while or do while.

Well, this seems to be a tricky one for the first time. Counting and no loops? The answer: Recursion. Here’s the (recursive) function:

public void printOddNumbers(int number, int max) {
    if (number > max) {
        return;
    }

    if (number % 2 == 0) {
        System.out.println(number);
    }

    printOddNumbers(number + 1, max);
}
jshell> printOddNumbers(0, 10)
0
2
4
6
8
10

jshell>

he method accepts two parameters: The first for the actual number, the second one holds the maximum value (which is 10).

If the current number is bigger than 10, then return, the function is over.

The current number is an odd number if it can be divided by two without remainder. Should this be the case, let’s print it.

And here’s the trick: Increment the current number by one and call ourselves again! The next run of the printOddNumbers function will start with the number variable set to 2, then 3, and so on.

Check if two Strings are Mirror of Each Other

The last exercise for today is as follows:

Write a function that determines whether two given words are mirror of each other!

For example, now and won are mirror words of each other. Our first solution to this problem:

public boolean mirrorWords(String word1, String word2) {
    if (word1 == null || word2 == null || word1.length() != word2.length()) {
        return false;
    }

    for (int i = 0, j = word2.length() - 1; i < word1.length(); i++, j--) {
        if (word1.charAt(i) != word2.charAt(j)) {
            return false;
        }
    }

    return true;
}

Following the defensive programming guidelines,we first carry out a quick test to verify that the parameters are not null.

Also, if the length of the two words is not the same, we can also immediately return with false.

The loop logic is telling you the following: With two loop variables, i starting from the beginning of the first word, and variable j starting from the last position of the second word, compare each character pointed by i and j loop variables. At the first mismatch we can state they are not mirror words, so return with false.

If the loop ends, it means the words are mirror words.

jshell> mirrorWords("now", "won")
$16 ==> true

jshell>

In the previous example, we learned how to use StringBuilder to reverse its parameter. We could use it here too:

public boolean mirrorWordsAlternative(String word1, String word2) {
    if (word1 == null || word2 == null || word1.length() != word2.length()) {
        return false;
    }

    return word1.equals(new StringBuilder(word2).reverse().toString());
}
jshell> mirrorWordsAlternative("won", "now")
$17 ==> true

jshell>

That’s a short an elegant solution.

Summary

That’s it for this week! I hope the code samples with the explanations help you understand these exercises. In case you’re requested to solve these problems in an interview session, the interviewers may be rather interested in seeing your algorithmic skills. That said, be sure that you understand each version. You can impress the interviewers by knowing the one-liner version of the reverse string method for example, but it’s always worth knowing the general algorithmic solution to these problems.