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.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.javacodeexamples.stringexamples; public class StringReverse { public static void main(String[] args) { String str = "Hello World"; String reverseStr = new StringBuilder(str).reverse().toString(); System.out.println(reverseStr); } } |
Output
1 |
dlroW olleH |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
String str = "Hello World"; //get char array from string char[] chars = str.toCharArray(); String strReversedString = ""; //iterate the array in reverse order for(int i = chars.length - 1 ; i >= 0 ; i--) { //append the characters one by one strReversedString = strReversedString + chars[i]; } System.out.println(strReversedString); |
Output
1 |
dlroW olleH |
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.
1 2 3 4 5 6 7 8 9 10 |
String str = "Hello World"; char[] chars = str.toCharArray(); StringBuilder sbReverse = new StringBuilder(); for(int i = chars.length - 1 ; i >= 0 ; i--) { sbReverse.append(chars[i]); } System.out.println(sbReverse.toString()); |
Output
1 |
dlroW olleH |
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.