Reverse a String in Java in 10 different ways
This post will discuss how to reverse a string in Java in 10 different ways. For example, the reverse of “Techie Delight” is “thgileD eihceT”.
We have covered 10 different ways (and 15 different implementations) to reverse a string in Java:
- Using StringBuilder/StringBuffer
- Using Stack
- Using Java Collections Framework
reverse()method - Using character array
- Using character array and swap()
- Using + (string concatenation) operator
- Using Unicode Right-to-left override (RLO) character
- Using a Byte Array
- Using Recursion
- Using
substring()method
1. Using StringBuilder/StringBuffer
We can use the StringBuilder.reverse() method to reverse a Java string efficiently. Alternatively, we can also use the StringBuffer.reverse() method. Using StringBuilder is suggested as it’s not synchronized and faster than StringBuffer.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Main { // Method to reverse a string in Java using `StringBuilder` public static String reverse(String str) { return new StringBuilder(str).reverse().toString(); } public static void main(String[] args) { String str = "Techie Delight"; // Note that string is immutable in Java str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
2. Using Stack
We can take the help of Stack data structure to reverse a string in Java. Following are the complete steps:
- Create an empty stack of characters.
- Convert given string into character array using
String.toCharArray()method and push each character of it into the stack. - Remove characters from the stack until it becomes empty and assign them back to the character array. As stack follows FILO order, characters will be inserted in the reverse order.
- Finally, convert the character array into string using
String.copyValueOf(char[])and return the formed string.
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import java.util.Stack; class Main { // Method to reverse a string in Java using a stack and character array public static String reverse(String str) { // base case: if the string is null or empty if (str == null || str.equals("")) { return str; } // create an empty stack of characters Stack<Character> stack = new Stack<Character>(); // push every character of the given string into the stack char[] ch = str.toCharArray(); for (int i = 0; i < str.length(); i++) { stack.push(ch[i]); } // start from index 0 int k = 0; // pop characters from the stack until it is empty while (!stack.isEmpty()) { // assign each popped character back to the character array ch[k++] = stack.pop(); } // convert the character array into a string and return it return String.copyValueOf(ch); } public static void main(String[] args) { String str = "Techie Delight"; str = reverse(str); // string is immutable System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
We can also use StringBuilder instead of a character array, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import java.util.Stack; class Main { // Method to reverse a string in Java using `Stack` and `StringBuilder` class public static String reverse(String str) { // base case: if the string is null or empty if (str == null || str.equals("")) { return str; } // create an empty stack of characters Stack<Character> stack = new Stack<Character>(); // push every character of the given string into the stack for (int i = 0; i < str.length(); i++) { stack.push(str.charAt(i)); } // pop characters from the stack and append them into `StringBuilder` StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.append(stack.pop()); } // convert `StringBuilder` to `String` and return return sb.toString(); } public static void main(String[] args) { String str = "Techie Delight"; str = reverse(str); // String is immutable System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
3. Using Java Collections Framework reverse() method
We can use Collections.reverse() to reverse a string in Java. Following are the complete steps:
- Create an empty
ArrayListof characters and initialize it with characters of the given string usingString.toCharArray(). - Reverse the list using
java.util.Collectionsreverse()method. - Finally, convert the
ArrayListinto a string usingStringBuilderand return it.
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.ListIterator; class Main { // Method to reverse a string in Java using `Collections.reverse()` public static String reverse(String str) { // base case: if the string is null or empty if (str == null || str.equals("")) { return str; } // create an empty list of characters List<Character> list = new ArrayList<Character>(); // push every character of the given string into it for (char c: str.toCharArray()) { list.add(c); } // reverse list using `java.util.Collections` `reverse()` Collections.reverse(list); // convert `ArrayList` into string using `StringBuilder` and return it StringBuilder builder = new StringBuilder(list.size()); for (Character c: list) { builder.append(c); } return builder.toString(); } public static void main(String[] args) { String str = "Techie Delight"; // String is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
The above solution first converts ArrayList into StringBuilder, then StringBuilder into a string. We can directly convert ArrayList into a string by removing square brackets, commas, and single space from it. The following code uses String.replaceAll() to achieve that. But this approach is highly inefficient and should be avoided at all costs.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import java.util.List; import java.util.ArrayList; import java.util.Collections; class Main { // Method to reverse a string in Java using `Collections.reverse()` public static String reverse(String str) { // return if the string is null or empty if (str == null || str.equals("")) { return str; } // create an empty list of characters and push every // character of the given string into it List<Character> list = new ArrayList<Character>(); for (char c: str.toCharArray()) { list.add(c); } // reverse list using `java.util.Collections` `reverse()` Collections.reverse(list); // `list.toString()` is [t, h, g, i, l, e, D, , e, i, h, c, e, T] // convert `list.toString()` to valid string return list.toString() .replaceAll("[,\\[\\]]", "") // t h g i l e D e i h c e T .replaceAll(" ", "@") // t h g i l e D@ e i h c e T .replaceAll(" ", "") // thgileD@eihceT .replaceAll("@", " "); // thgileD eihceT } public static void main(String[] args) { String str = "Techie Delight"; // String is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
4. Using character array
We know that we cannot make any change in the String object as string is immutable in Java. But we can use a character array that can be modified easily:
- Create an empty character array of the same size as that of the given string.
- Fill the character array backward with characters of the given string.
- Finally, convert the character array into string using
String.copyValueOf(char[])and return it.
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class Main { // Method to reverse a string in Java using a character array public static String reverse(String str) { // return if the string is null or empty if (str == null || str.equals("")) { return str; } // get string length int n = str.length(); // create a character array of the same size as that of string char[] temp = new char[n]; // fill character array backward with characters in the string for (int i = 0; i < n; i++) { temp[n - i - 1] = str.charAt(i); } // convert character array to string and return it return String.copyValueOf(temp); } public static void main(String[] args) { String str = "Techie Delight"; // String is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
5. Using character array and swap() method
Following is another efficient way to reverse a string in Java using character array:
- Create a character array and initialize it with characters of the given string using
String.toCharArray(). - Start from the two endpoints
landhof the given string. Run the loop till two endpoints intersect(l <= h). In each iteration of the loop, swap values present at indexesl&hand incrementl& decrementh. - Finally, convert the character array into string using
String.copyValueOf(char[])and return.
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class Main { // Method to reverse a string in Java using a character array public static String reverse(String str) { // return if the string is null or empty if (str == null || str.equals("")) { return str; } // create a character array and initialize it with the given string char[] c = str.toCharArray(); for (int l = 0, h = str.length() - 1; l < h; l++, h--) { // swap values at `l` and `h` char temp = c[l]; c[l] = c[h]; c[h] = temp; } // convert character array to string and return return String.copyValueOf(c); } public static void main(String[] args) { String str = "Techie Delight"; // String is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
6. Using + (string concatenation) operator
We can use the string concatenation operator + to reverse a string in Java by reading characters from the end of it and concatenating them at the beginning of a new string. Please note that to increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the total number of intermediate string objects created by evaluation of an expression[1].
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Main { // Reverse a string in Java using the string concatenation operator public static String reverse(String str) { // return if the string is null or empty if (str == null || str.equals("")) { return str; } // variable to store the reversed string String rev = ""; // use string concatenation operator to build reversed string by // reading character from the end of the original string for (int i = str.length() - 1; i >=0 ; i--) { rev += str.charAt(i); } return rev; } public static void main(String[] args) { String str = "Techie Delight"; str = reverse(str); // string is immutable System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
7. Using Unicode Right-to-left override (RLO) character
We can use Unicode Right-to-left override (RLO) character to convert a string into its reverse, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Main { // Method to reverse a string in Java by Unicode // Right-to-left Override (RLO) character public static String reverse(String str) { return "\u202E" + str; } public static void main(String[] args) { String str = "Techie Delight"; // string is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
8. Using a Byte Array
The idea is very simple – convert the given string into bytes, and then in-place rearranges the byte array, as shown in Approach #5. Finally, we convert the byte array back into a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import java.util.Arrays; class Main { // Method to reverse a string in Java using a byte array public static String reverse(String str) { // return if the string is null or empty if (str == null || str.equals("")) { return str; } // convert string into bytes byte[] bytes = str.getBytes(); // start from the two endpoints `l` and `h` of the given string // and increment `l` & decrement `h` at each iteration of the loop // until two endpoints intersect (l >= h) for (int l = 0, h = str.length() - 1; l < h; l++, h--) { // swap values at `l` and `h` byte temp = bytes[l]; bytes[l] = bytes[h]; bytes[h] = temp; } // convert byte array back into a string return new String(bytes); } public static void main(String[] args) { String str = "Techie Delight"; // String is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
9. Using Recursion
As seen in Approach #2, we can easily reverse a string in Java using the stack data structure. As the stack is involved, we can easily convert the code to use the recursion call stack. As string is immutable, we first convert the given string into a character array, then reverse the character array and finally convert the character array back into a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
class Main { static int i = 0; // Recursive method to reverse a string in Java using a static variable private static void reverse(char[] str, int k) { // if the end of the string is reached if (k == str.length) { return; } // recur for the next character reverse(str, k + 1); if (i <= k) { char temp = str[k]; str[k] = str[i]; str[i++] = temp; } } public static String reverse(String str) { // base case: if the string is null or empty if (str == null || str.equals("")) { return str; } // convert string into a character array char[] A = str.toCharArray(); // reverse character array reverse(A, 0); // convert character array into the string return String.copyValueOf(A); } public static void main(String[] args) { String str = "Techie Delight"; // string is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
The above solution uses a static variable, which is not recommended. We can easily solve this problem without using any static variable. This approach is almost similar to Approach #3 discussed here.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
class Main { // Recursive method to reverse given character array private static void reverse(char[] A, int l, int h) { if (l < h) { char ch = A[l]; A[l] = A[h]; A[h] = ch; reverse(A, l + 1, h - 1); } } // Recursive method to reverse a string in Java public static String reverse(String str) { // base case: if the string is null or empty if (str == null || str.equals("")) { return str; } // convert string into a character array char[] A = str.toCharArray(); // reverse character array reverse(A, 0, A.length - 1); // convert character array into the string return String.copyValueOf(A); } public static void main(String[] args) { String str = "Techie Delight"; // string is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
10. Using substring() method
We can use String.substring(int, int) method to recursively reverse a string in Java. The following code uses the String.charAt(int) method to isolate the first or last character of the string and recur for the remaining string using substring().
⮚ Approach #1
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Main { // Method to reverse a string in Java using recursion private static String reverse(String str) { // base case: if the string is null or empty if (str == null || str.equals("")) { return str; } // last character + recur for the remaining string return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1)); } public static void main(String[] args) { String str = "Techie Delight"; // string is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
⮚ Approach #2
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Main { // Method to reverse a string in Java using recursion public static String reverse(String str) { // base case: if the string is null or empty if (str == null || str.equals("")) { return str; } // isolate the first character and recur for the remaining string return reverse(str.substring(1)) + str.charAt(0); } public static void main(String[] args) { String str = "Techie Delight"; // string is immutable str = reverse(str); System.out.println("The reverse of the given string is: " + str); } } |
Output:
The reverse of the given string is: thgileD eihceT
That’s all about different ways to reverse a String in Java.
Reference: String Javadoc SE 8
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)