Java Reverse String Example

Java reverse string example shows how to reverse a string. This example also shows how to reverse words as well as reverse the order of the individual words of the string in Java.

How to reverse a String in Java?

1) Using the StringBuilder or StringBuffer class

The String class does not provide any methods to reverse a string. However, the StringBuilder class does. Create a new StringBuilder object from the string, use the reverse method of StringBuilder class to reverse the StringBuilder content, and then convert StringBuilder to String object using the toString method.

This method reverses the content of the StringBuilder.


2) Using the charAt method of the String class (without using the reverse method)


Note: This solution is not compatible with the Unicode characters as they are formed using a pair of characters. This solution reverses the pair and will corrupt the characters.

3) Using Apache Commons Library

If you are using the Apache Commons library, you can use the reverse method of the StringUtils class to reverse a string.


How to reverse the words of string in Java?

Suppose you want to reverse individual words of the string and not the entire string then the above given solutions will not work as they reverse the entire string. For example, if the input string is “Hello World”, the output should be “olleH dlroW” not “dlroW olleH”. Use below given solution instead.


How to reverse the order of the words in a string?

Use the below given solution if you want to reverse the order of the words in a string. For example, if the string contains “Java String Reverse”, then the output should be “Reverse String Java”. So basically, we are reversing the order of the words so that the first word comes last, the second word comes second last and so on.


Note: The StringBuilder class is not available in Java JDK 1.4 and below. Use the StringBuffer class instead.

This example is a part of the Java String tutorial.

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

About the author



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 *

Online Shopping