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
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.
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.
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.
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.