Reversing a string is a common coding problem that often comes up when you’re learning about algorithms or when you’re picking up a new programming language. It is also one of the most frequently asked questions in coding interviews for Java developers where interviewers may ask you to reverse a string in a variety of ways.
In this tutorial, we will present a comprehensive guide on how to reverse a string in Java.
Firstly, we will introduce the Java string data type along with its features and properties. Then, we will show nine different methods with simple, yet efficient code examples that you can use to write a program to reverse a string in Java.
Note: this tutorial and the methods we cover were coded with Java 8.
Strings in Java
The string is an inescapable data type when writing any application or software that needs to store text-like data.
In Java, the string is an object that represents a sequence of characters (Java char data type). In many ways, strings can be seen as a data structure since they are an array (or sequence) of characters (chars). And like arrays, strings are one of the most widely used data structures.
We use the Java string class (java.lang.String) to create a string object. This class implements Serializable, Comparable, and CharSequence interfaces, and it also provides numerous built-in methods such as compare(), concat(), split(), equals(), length(), replace(), compareTo(), intern(), substring(), etc.
Let’s summarize some of the most important properties of Java strings:
- There are two ways to create Java string objects:
- A string literal: This is stored and managed by the Java Virtual Machine (JVM) in a special memory area known as the "string constant pool"
- The ‘new’ keyword: The string object is created by the JVM in the normal (non-pool) heap memory
- Java makes sure that string objects are immutable (cannot be altered) with these features:
- ClassLoader: ensures that the string object class is always loaded
- Thread-Safe: ensures the synchronization of a string object when it’s shared by multiple threads
- Security: ensures deterministic and error-free behavior for classes and objects that use string arguments to define and manipulate operations
- Heap Space: ensures efficient use of heap memory by the JVM
- Java also provides the StringBuffer (introduced in Java 1.0) and StringBuilder (introduced in Java 1.5) classes to create string objects. Both these and the String class implement the CharSequence interface
- Java String objects are immutable, which means they cannot be changed. So, every time we ‘change’ a string object, we’re actually producing a new string instance
- The Java StringBuilder and StringBuffer classes are mutable versions (can be changed) of the String class
- Compared with the String class, StringBuffer and StringBuilder objects are faster and more efficient at memory management
- The StringBuilder and StringBuffer classes have a built-in .reverse() method, but the String class does not
Different Techniques To Reverse a String in Java
We’ll use a Java String object to represent a word and we’ll look at the most common string reverse methods to invert the character order. You can then use these techniques in your own Java projects.
1) Reverse a String Using a Loop
We’ll need to create a new empty String object to store the reversed string because we cannot alter or reverse the original string in place due to its immutability.
With the loop, we can use a for loop or a while loop to iterate over each of the string characters. In this example we’ll use a for loop.
Next, we need to configure our loop to access the string characters in reverse order. After all, we want a Java program to reverse a string!
We can do this with a decrementing loop: this starts at the last index (character) of the string object, then decrements on each loop until it reaches the 0th index (the first char).
To find the last char’s index we can use Java’s built-in .length() string method to find the length of our string, and then we subtract 1 to account for 0 indexing. Our for loop counter variable will start at this index and decrement by -1 in each iteration.
Having set up the loop, we can iterate over the string and access the chars in reverse order. The final step is to store the chars in the empty string we created. To do this, we concatenate each char with the current version of the string. When we’re finished we’ll have a new string object with the chars in reverse.
Code Example Using For Loop:
public class ReverseStringHackrIO {
public static void main(String[] args) {
String stringExample = "HackrIOTutorial";
System.out.println("Original string: "+stringExample);
int n = stringExample.length(); // Length of original string
String reversedString =""; // Empty string to store reversed chars
char ch; // Char to store current string character
for (int i = n - 1; i >= 0; i--) {
ch = stringExample.charAt(i); // Return & store current char
reversedString = reversedString + ch; // Append char to end
}
System.out.println("Reversed string: "+ reversedString);
}
}
Output:
Original string: HackrIOTutorial
Reversed string: lairotuTOIrkcaH
2) Reverse a String by Swapping Characters
For this approach we’ll use the built-in .toCharArray() function from the String class to convert a string into a character array. We’ll then use a for loop to iterate over the array, but importantly, we will move ‘inwards’ from both the left and right ends of the array in each loop.
To do this, we need the last index of the array which we find via the built-in .length() method: this returns the number of elements in the array. We then subtract 1 from this value to get the last index position and we’ll assign this to ‘fin’.
We can then set up our loop:
- Initialize a ‘start’ counter variable to represent the current leftmost index (starts at 0)
- Check if the ‘start’ variable is less than the current rightmost index (starts at last index)
- If true, increment the ‘start’ variable by 1, and decrement the ‘fin’ variable by -1
So, we’ll continually adjust our ‘start’ and ‘fin’ variables on each loop. It helps to visualize this like a ‘pincering’ movement as we move closer and closer to the middle element of the array.
But before we get there, we ‘swap’ the characters at the current leftmost and rightmost positions on each loop. This is just a case of:
- Storing the char at the current ‘start’ index in a temp variable
- Swapping the char in the current ‘start’ index with the char at the current ‘fin’ index
- Swapping the char at the current ‘fin’ index with our temp variable (which is our original ‘start’ index char)
After we’ve looped over the elements, we’ll have reversed the chars in the array. Finally, we’ll convert the array back to a string using the built-in String.valueOf() function.
public class ReverseStringHackrIO {
public static void main(String[] args) {
String stringExample = "HackrIOTutorial";
System.out.println("Original string: " + stringExample);
// Converting String to Character Array
char str[] = stringExample.toCharArray();
int start, fin = 0;
fin = str.length - 1; // Length of character array
for (start = 0; start < fin; start++, fin--) {
// Swap characters from leftmost and rightmost
char temp = str[start];
str[start] = str[fin];
str[fin] = temp;
}
// Converting characterArray to String
String reversedString = String.valueOf(str);
System.out.println("Reversed string: "+reversedString);
}
}
Output:
Original string: HackrIOTutorial
Reversed string: lairotuTOIrkcaH
3) Reverse a String Using the StringBuilder Class
Another way to reverse a string in Java is to use the built-in reverse() method from the StringBuilder class (not available with the String class).
We start by creating an empty StringBuilder object which we’ll use to store our original string. We then ‘convert’ our String object into a StringBuilder by invoking .append() on our empty StringBuilder.
It’s then a matter of calling .reverse() on our StringBuilder object to reverse the characters in the string. This is allowed because StringBuilder objects are mutable, which means we can change them in place.
Finally, we convert our reversed StringBuilder back to a String object and print the result.
StringBuilder Code Example 1:
public class ReverseStringHackrIO {
public static void main(String[] args) {
String stringExample = "HackrIOTutorial";
System.out.println("Original string: " + stringExample);
// Declaring StringBuilder + converting string to StringBuilder
StringBuilder reverseString = new StringBuilder();
reverseString.append(stringExample);
reverseString.reverse(); // Reversing the StringBuilder
// Converting StringBuilder to String
String result = reverseString.toString();
System.out.println("Reversed string: "+result);
}
}
Another way to use StringBuilder is to bypass .append() altogether. To do this, we just use our original String object as an argument for the StringBuilder constructor. We can then continue with the same steps shown code example 1:
StringBuilder Code Example 2:
public class ReverseStringHackrIO {
public static void main(String[] args) {
String stringExample = "HackrIOTutorial";
System.out.println("Original string: " + stringExample);
// Declaring StringBuilder + converting string to StringBuilder
StringBuilder reverseString = new StringBuilder(stringExample);
reverseString.reverse(); // Reversing the StringBuilder
// Converting StringBuilder to String
String result = reverseString.toString();
System.out.println("Reversed string:" +result);
}
}
Output for code examples 1 and 2:
Original string: HackrIOTutorial
Reversed string: lairotuTOIrkcaH
4) Reverse a String Using ArrayList Object
This time, we’ll use a character array and an ArrayList object (notice how we import Java’s util.ArrayList package).
To start, we’ll convert our String object into a character array with the .toCharArray() method from the String class. We’ll then create a new ArrayList object (of type character) to store the chars from our character array via a for loop. This loop iterates through the chars in our character array and adds these to the ArrayList.
Next, we’ll reverse our ArrayList using the built-in .reverse() method from Java’s util.Collections class ( imported at the top of the program). We then pass our ArrayList object as an argument to this method which reverses the elements in place.
Finally, we print the reversed elements in the ArrayList with the help of a ListIterator object and its .listIterator() function (both imported at the top of the program). To do this, we’ll create a new ListIterator instance and assign it the result of calling .listIterator() on our ArrayList.
The last step is a while loop which prints out each item in the ListIterator until there are no elements to return. Note the use of System.out.print here as we don’t want a new line after each character.
ArrayList Code Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
public class ReverseStringHackrIO {
public static void main(String[] args) {
String stringExample = "HackrIOTutorial";
System.out.println("Original string: " + stringExample);
char str[] = stringExample.toCharArray();
// Declare ArrayList of Chars
List<Character> listChar = new ArrayList<>();
// Iterate over Character Array & add char to ArrayList
for(int i = 0; i < str.length; i++){
listChar.add(str[i]);
}
Collections.reverse(listChar); // Reversing list
int size = listChar.size(); // size of ArrayList
System.out.print("Reversed string: ");
//ListIterator Object to iterate over reversed ArrayList.
ListIterator<Character> liter = listChar.listIterator();
while (liter.hasNext()){
// Print characters from reversed ArrayList
System.out.print(liter.next());
}
}
}
Output:
Original string: HackrIOTutorial
Reversed string: lairotuTOIrkcaH
5) Reverse a String Using StringBuffer
In this example we use the StringBuffer class and its built-in reverse() method to quickly return the reverse of a string in Java. This is similar to the StringBuilder approach in method 3 as the StringBuffer is also mutable (can be altered in place). Another advantage to using the StringBuffer is a reduction in memory requirements when compared with the String class.
So, we convert our String object to a StringBuffer object by passing the string as a constructor argument. We then invoke the .reverse() function on the StringBuffer to reverse the string’s characters. Finally, we print the result.
StringBuffer Code Example:
public class ReverseStringHackrIO {
public static void main(String[] args) {
String stringExample = "HackrIOTutorial";
System.out.println("Original string: " + stringExample);
// Conversion from String object to StringBuffer
StringBuffer reversedSB = new StringBuffer(stringExample);
reversedSB.reverse(); // Reverse the string
System.out.println("Reversed String: " + reversedSB);
}
}
Output:
Original string: HackrIOTutorial
Reversed string: lairotuTOIrkcaH
6) Reverse a String Using a ByteArray
This approach uses a ByteArray object to store the bytes of a String object in reverse order.
We’ll start by using the .getBytes() string method to encode our String object into an array of bytes, which we’ll then assign to a byte[] array variable. Next, we’ll create a temporary byte[] array called ‘result’ and we’ll size this to equal the length of the original string. We’ll use this later to store the bytes in reverse order.
The final step is to iterate over the byteArray that we populated with our string bytes, but in reverse order. We do this by subtracting the loop counter value from the length of the byteArray -1. Essentially, this returns the last index and it continually decrements until we reach index 0.
By iterating in reverse, we can add these bytes to our ‘result’ array which reverses the original bytes. Finally, we convert the ‘result’ array back to a String object to represent our reversed string.
ByteArray Code Example:
public class ReverseStringHackrIO {
public static void main(String[] args) {
String stringExample = "HackrIOTutorial";
System.out.println("Original string: " + stringExample);
byte[] byteArray = stringExample.getBytes();
byte[] result = new byte[byteArray.length];
// Store bytes in reverse order
for (int i = 0; i < byteArray.length; i++){
result[i] = byteArray[byteArray.length - i - 1];
}
System.out.println("Reversed string: " + new String(result));
}
}
Output:
Original string: HackrIOTutorial
Reversed string: lairotuTOIrkcaH
7) Reverse a String Using Java Stack Object
On this occasion we’ll use a Stack data structure to reverse a String object. We’ll import Java’s util.Stack class to create our stack, and we’ll get the string reverse with these steps:
- Create an empty Stack object of characters
- Call the Stack's built-in .push() method to push each char from a string onto the stack
- Pop characters from the Stack: this returns them in reverse (Stacks are Last-In-First-Out = LIFO)
- Concatenate the popped chars with a String object to produce a reversed string
So, we start by creating an empty Stack of chars, and then we loop through the chars in our String to push them onto the Stack. We’ll concatenate each char that we pop from the Stack with a String object that we’ll initially set as blank, which means this string will ‘grow’ with each loop.
We’ll use a while loop to pop chars from the Stack until the .isEmpty() Stack method returns true. At this point, we’ve popped all of our chars, the Stack has been emptied, and we have reversed the string.
Stack Code Example:
Import java.util.Stack
public class ReverseStringHackrIO {
public static void main(String[] args) {
String stringExample = "HackrIOTutorial";
System.out.println("Original string: " + stringExample);
// Create empty Stack of chars
Stack<Character> stack = new Stack<>();
for(int i=0; i < stringExample.length(); i++){
// Push chars from string onto Stack
stack.push(stringExample.charAt(i));
}
// Empty string to store popped chars
String reversedString = "";
// Pop chars from Stack in reverse order
while(!stack.isEmpty()){
reversedString += stack.pop();
}
System.out.println("Reversed string: "+reversedString);
}
}
Output:
Original string: HackrIOTutorial
Reversed string: lairotuTOIrkcaH
8) Reverse a String Using Recursion
A classic approach to string reversal is to use recursion. This means that we’ll need to define a recursive function that continually calls itself until we reach a base case, at which point we’ll return and make our way back through the Java call stack of recursive calls.
To design our recursive function, we’ll use a similar approach to method 2. Have a quick look to refresh your memory: TL-DR, we swapped the current leftmost and rightmost characters via a for loop that moved inwards to the middle element of an array.
Okay, the first step is to set our base case. If we look at method 2, we stopped when we hit the middle element of the array. So it makes sense to use this as our base case.
We’ll then need our recursion to move inwards towards the middle element, which means it will be a ‘reducing’ function. Looking at method 2, it makes sense for us to track the current leftmost and rightmost elements. We’ll do this with a reference value that we pass to a recursive function, and this will be used to reduce the problem as we move toward the middle element.
Okay, we’ve got the general idea, so let’s implement this with the following:
- Find the length of the character array and use this to find the middle element index
- Check the base case: is the passed start index equal to the middle index?
- If true, return
- Else, continue below
- Swap the current leftmost and rightmost chars via:
- Store char at the current leftmost index in a temp variable
- Swap char at current leftmost index with char at current rightmost index
- Swap char at the current rightmost index with temp variable
- Recursively call function with: character array and index value incremented by +1
If we look at the code for our recursive function, we need to pass in a character array and a start index value as arguments. To ensure our recursive call ‘reduces’ the problem, we pass in incrementally larger ‘start’ index values. So, when we calculate our current leftmost and rightmost index values, these will slide toward the middle of the character array.
The function will finally return when the base case is true: when the start index is equal to the middle element. At this point, the character array will reflect a reversed string.
And that’s all there is to it! Of course, we need to define our input string and convert this to a character array (using .toCharArray()), which we’ll do in our Main method. We’ll pass this array along with a start index of 0 to the recursive function.
Once the recursion has completed, we can print the string reverse by printing the result of calling the .valueOf() method from the String class on our array.
Recursion Code Example:
public class ReverseStringHackrIO {
static void recursiveReverse(char[] str, int i){
int n = str.length;
// Base case: return if start index == middle element
if (i == n / 2){
return;
}
// Swap current leftmost & rightmost characters
char temp = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = temp;
// Make recursive call with char array & start index +1
recursiveReverse(str, i + 1);
}
public static void main(String[] args) {
String stringExample = "HackrIOTutorial";
System.out.println("Original string: " + stringExample);
// Convert string to char array
char[] str = stringExample.toCharArray();
// Call recursive function with char array & index 0
recursiveReverse(str,0);
System.out.println("Reversed string: "+ String.valueOf(str));
}
}
Output:
Original string: HackrIOTutorial
Reversed string: lairotuTOIrkcaH
9) Reverse a String With Apache Commons Library
Apache Commons is a popular Java library that provides several utility classes that we can use to manipulate strings. In this example, we’ll use the library’s StringUtils class and its reverse() method (much like the Java StringBuilder and StringBuffer) to reverse a string in Java.
To use the library, we need to add it using its Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
After adding the library, we can easily pass any String object that we’d like to reverse as an argument to StringUtils.reverse(). Using this library also gives us the added benefit of ‘null-safe’ operations, which means that we don’t need to treat edge cases separately.
Conclusion
In this tutorial, we've covered nine of the most important techniques to reverse a string in Java. The options we covered include:
- Iterative methods that access string characters in reverse order, allowing us to ‘store them’ in an output variable
- If we use the String object, we can concatenate the reversed chars to an empty String
- if we convert to a character array, we can store reversed elements or bytes in a results array
- Iterative method to ‘swap’ characters from the current leftmost and rightmost positions
- Mutable StringBuffer and StringBuilder classes with built-in reverse() functions
- Java Collections class and its built-in reverse() method for an ArrayList
- The Stack data structure and its LIFO characteristics
- Recursion to ‘reduce’ our problem size as we recursively swap the current leftmost and rightmost chars from a character array
- Third-party Apache Commons library which provides utility classes with built-in reverse()
Another thing you should consider when deciding how to reverse a string in Java relates to performance. If you can, it’s always best to strive for linear time complexity when reversing strings. This applies to an iterative approach, recursive approach, or when using built-in Java class reverse methods.
With that said, we highly recommend using the built-in reverse methods from the StringBuffer and StringBuilder classes for optimal performance when reversing strings in Java.
If you’re new to Java or you’ve only just started learning, head over to our Java cheat sheet. or check out the Java Masterclass on Udemy to help strengthen your knowledge on the techniques used within these string reverse methods.
Frequently Asked Questions
1. What is a String in Java?
Strings in Java are immutable (cannot be modified or changed) non-primitive data types that store a sequence of characters.
2. Is There a Method to Reverse a String in Java?
The Java String class does not have a built-in method to directly reverse a string. Instead, you can use the StringBuffer or StringBuilder classes which offer a reverse() function. Alternatively, you also can use other algorithms and data structures to reverse a string without these methods.
3. How Many Ways Can You Reverse a String in Java?
You can use iterative methods that create new String objects to store a reversed string, or methods that swap the current leftmost and rightmost String characters via a temporary variable. Alternatively, you can use the StringBuffer and StringBuilder classes to access a built-in reverse() function, or use the Collections class to access a reverse() method for List data structures. You can also use recursion, or a Stack object to take advantage of its LIFO property to reverse characters. Finally, you can also use a third-party library like Apache Commons.
4. What is the Reverse Method in Java?
When dealing with String objects, there is no reverse method. But, if we can use the StringBuffer or StringBuilder classes we can use a built-in reverse() method. This is allowed because these classes are mutable.
5. How do you Reverse a Name in Java?
There are various ways to reverse String objects such as a person’s name in Java. You can use iterative methods to access and store characters in reverse, you can use loops to swap characters; you can use built-in reverse methods from the StringBuffer, StringBuilder, or Collections classes; you can use a Stack; you can use recursion, or you can use a third-party library like Apache Commons.