How do I reverse a String?
Author: Deron Eriksson
Description: This Java example shows how to reverse a String.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

Reversing the order of a String can be performed in a variety of ways. The ReverseStringTest class demonstrates two simple techniques. Technique one is to convert a String to a StringBuffer and call the reverse() method on the StringBuffer. The toString() method of the StringBuffer then returns the reversed String. The second technique demonstrated uses the reverse() method of the StringUtils class from Commons LangS.

package test;


import org.apache.commons.lang.StringUtils;

public class ReverseStringTest {

	public static void main(String[] args) throws IOException {

		String str = "Let's reverse this string";
		System.out.println("Original:" + str);

		StringBuffer sb = new StringBuffer(str);
		System.out.println("Reversed #1:" + sb.reverse().toString());

		System.out.println("Reversed #2:" + StringUtils.reverse(str));



The console output from ReverseStringTest is shown here:


Original:Let's reverse this string
Reversed #1:gnirts siht esrever s'teL
Reversed #2:gnirts siht esrever s'teL