Skip to content

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.

Output

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

Output

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.

Output

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.

Output

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.

Output

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

Leave a Reply

Your email address will not be published.