Skip to content

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

Leave a Reply

Your email address will not be published.