Java String Handling

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?

There are several ways in which you can reverse String in Java.

1) Using StringBuilder or StringBuffer class

String class does not provide any methods to reverse the String. However, StringBuilder class does. Use reverse method of StringBuilder class to reverse String.

This method reverses the content of the StringBuilder.


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


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

3) Using Apache Commons Library

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


How to reverse words of String in Java?

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


How to reverse the order of the words in String?

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


StringBuilder class is not available in Java JDK 1.4 and below. Use StringBuffer class instead.

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