Java String Reverse

Java String reverse example shows how to reverse a String in Java. It also shows how to reverse a string using StringBuilder, char array, and byte array.

How to reverse a String in Java?

There are several ways using which we can reverse a string in Java as given below.

1. Using StringBuilder

The easiest way to reverse a string is to use the StringBuilder class (or StringBuffer class if you are using Java version below 1.6). This class provides the reverse method that reverses the content. We can make use of this method to reverse the string as given below.

Output

We first created a new StringBuilder object from the string, then we reversed it using the reverse method, then we converted the reversed content back to the string.

2. Using the character array

We can first convert the String to a character array using the toCharArray method. Once we get the char array, we can loop through it in reverse order and create a string from that as given below.

Output

Please note that this solution does not work for the Unicode characters having the surrogate pairs. The reason being is, this solution will also reverse them that makes those characters having the pair in the wrong order.

Instead of appending the characters to a string, we can also use the StringBuilder object as given below.

Output

If you want to learn more about the string in Java, please visit the Java String Tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *