Reverse string

This example will show how to reverse a sequence of characters using java and apache commons. Reversing a string is a piece of logic used when determining if a phrase is a palindrome. For each snippet below, the set up method has created a String to represent a phrase of words and String to hold the characters of the phrase backwards.

Setup

private static final String PHRASE = "The dog barked at the mail man";
private static final String PHRASE_REVERSE = "nam liam eht ta dekrab god ehT";

Straight up Java

StringBuffer

This snippet will reverse a string using StringBuffer. We will create a StringBuffer by passing in a character sequence into the constructor then calling the reverse method which causes the characters to be returned in reverse order.

@Test
public void reverse_a_string_with_java () {

    StringBuffer buffer = new StringBuffer(PHRASE);

    String reversedString = buffer.reverse().toString();

    assertEquals(PHRASE_REVERSE, reversedString);
}

Recursion

This snippet will show how to reverse a string using recursion. Effective Java Item 51 states beware the performance of string concatenation so be cautious when using this approach as it hasn't been tested with a large string which could lead to performance implications.

public String reverseString(String s){
    if (s.length() == 0)
         return s;

    return reverseString(s.substring(1)) + s.charAt(0);
}

@Test
public void reverse_a_string_with_recurrsion () {

    String reversedString = reverseString(PHRASE);

    assertEquals(PHRASE_REVERSE, reversedString);
}

Reverse string using for loop

This snippet will show how reverse a String using a for loop. We will iterate over the phrase of words with a for loop in reverse order collecting each character into a StringBuffer.

@Test
public void reverse_string_for_loop() {

    StringBuffer reverse = new StringBuffer();
    for (int i = PHRASE.length() - 1; i >= 0; i--) {
        reverse.append(PHRASE.charAt(i));
    }
    assertEquals(PHRASE_REVERSE, reverse.toString());
}

Apache Commons

Using a apache commons StringUtils class we will reverse a string. The underlying implementation is using a StringBuilder and calling the reverse function.

@Test
public void reverse_a_string_with_apache_commons () {

    String reversedString = StringUtils.reverse(PHRASE);

    assertEquals(PHRASE_REVERSE, reversedString);
}