Reverse a string in Java
Last Updated :
03 Sep, 2024
Reversing a string is a common task in programming, often asked in interviews, and useful in various algorithms. In Java, there are multiple ways to reverse a string, each with its own advantages.
This article discusses different ways to reverse a string in Java with examples.

Prerequisite: String vs StringBuilder vs StringBuffer in Java
Before diving into the methods of reversing a string, it is essential to understand the differences between String, StringBuilder, and StringBuffer classes in Java:
- String Objects are Immutable: Once a
String object is created, it cannot be changed. Any modification to a string results in the creation of a new string. - StringBuilder and StringBuffer: Both are mutable, allowing changes to their content without creating new objects. However,
StringBuilder is not thread-safe, whereas StringBuffer is thread-safe.
To know more, read this String vs StringBuilder vs StringBuffer in Java
Key Differences:
- No reverse() Method in String: The
String class in Java does not have a built-in reverse() method, whereas StringBuilder and StringBuffer do. - toCharArray() Method: The
String class has a toCharArray() method, which converts a string to a character array, but StringBuilder and StringBuffer do not.
To deepen your understanding of reversing a string in Java, you might explore free Java programming course that cover these concepts.
Different Methods to Reverse a String in Java
Method 1: Using a “for" Loop
- The idea is to traverse the length of the string
- Extract each character while traversing
- Add each character in front of the existing string
Implementation:
Java
// Java Program to Reverse a Word
import java.io.*;
import java.util.Scanner;
class GFG {
public static void main (String[] args) {
String str= "Geeks", nstr="";
char ch;
System.out.print("Original word: ");
System.out.println("Geeks"); //Example word
for (int i=0; i<str.length(); i++)
{
ch= str.charAt(i); //extracts each character
nstr= ch+nstr; //adds each character in front of the existing string
}
System.out.println("Reversed word: "+ nstr);
}
}
OutputOriginal word: Geeks
Reversed word: skeeG
Explanation:
- This Java program reverses the word “Geeks.”
- It iterates through each character of the original string, adding each character to the front of a new string.
- This process effectively reverses the word. Finally, it prints both the original and the reversed words.
Complexities:
- Time Complexity: O(n), where n is the length of the input string.
- Space Complexity: O(n), since it creates a new string to store the reversed word.
Method 2: Converting String into Bytes
getBytes() method is used to convert the input string into bytes[].
- Create a temporary byte[] of length equal to the length of the input string.
- Store the bytes (which we get by using getBytes() method) in reverse order into the temporary byte[] .
- Create a new String abject using byte[] to store result.
Implementation:
Java
// Java program to ReverseString using ByteArray.
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
public static void main(String[] args)
{
String input = "GeeksforGeeks";
// getBytes() method to convert string
// into bytes[].
byte[] strAsByteArray = input.getBytes();
byte[] result = new byte[strAsByteArray.length];
// Store result in reverse order into the
// result byte[]
for (int i = 0; i < strAsByteArray.length; i++)
result[i] = strAsByteArray[strAsByteArray.length - i - 1];
System.out.println(new String(result));
}
}
Explanation:
- This program reverses a string by converting it to a byte array using the
getBytes() method. - Then stores the characters in reverse order in a new byte array.
- Finally, it prints the reversed string by converting the byte array back to a string.
Complexities:
- Time complexity: O(n), where n is the length of the string.
- Space complexity: O(n), since a new byte array is used to store the reversed string.
Method 3: Using built in reverse() method of the StringBuilder Class
String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder. After that, print out the characters of the reversed string by scanning from the first till the last index.
Implementation:
Java
// Java program to ReverseString using StringBuilder
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
public static void main(String[] args)
{
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1.reverse();
// print reversed String
System.out.println(input1);
}
}
Explanation:
- This program reverses a string using the StringBuilder class.
- The string is first appended to a StringBuilder object.
- And then the reverse() method is called to reverse the contents.
- Finally, the reversed string is printed.
Complexities:
- Time complexity: O(n), where n is the length of the string.
- Space complexity: O(n), since the
StringBuilder stores the reversed string.
Method 4: Converting String to Character Array
- First, convert String to character array by using the built in Java String class method toCharArray().
- Then, scan the string from end to start, and print the character one by one.
Implementation:
Java
// Java program to Reverse a String by
// converting string to characters one
// by one
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
public static void main(String[] args)
{
String input = "GeeksForGeeks";
// convert String to character array
// by using toCharArray
char[] try1 = input.toCharArray();
for (int i = try1.length - 1; i >= 0; i--)
System.out.print(try1[i]);
}
}
Explanation:
- This program reverses a string by first converting it into a character array using the
toCharArray() method. - It then iterates over the array in reverse order, printing each character to form the reversed string.
Complexities:
- Time complexity: O(n), where n is the length of the string.
- Space complexity: O(n), due to the character array used to store the string’s characters.
Method 5: Using ArrayList Object
Convert the input string into the character array by using toCharArray() built in method. Then, add the characters of the array into the ArrayList object. Java also has built in reverse() method for the Collections class. Since Collections class reverse() method takes a list object, to reverse the list, we will pass the ArrayList object which is a type of list of characters.
- We copy String contents to an object of ArrayList.
- We create a ListIterator object by using the listIterator() method on the ArrayList object.
- ListIterator object is used to iterate over the list.
- ListIterator object helps us to iterate over the reversed list and print it one by one to the output screen.
Implementation:
Java
// Java program to Reverse a String using ListIterator
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
public static void main(String[] args)
{
String input = "Geeks For Geeks";
char[] hello = input.toCharArray();
List<Character> trial1 = new ArrayList<>();
for (char c : hello)
trial1.add(c);
Collections.reverse(trial1);
ListIterator li = trial1.listIterator();
while (li.hasNext())
System.out.print(li.next());
}
}
Explanation:
- This program reverses a string by first converting it into a character array, then adding each character to a
List. - The
Collections.reverse() method is used to reverse the list, and a ListIterator is used to iterate through the reversed list, printing each character.
Complexities:
- Time complexity: O(n), where n is the length of the string.
- Space complexity: O(n), due to the list that stores the characters.
Method 6: Using StringBuffer
String class does not have reverse() method, we need to convert the input string to StringBuffer, which is achieved by using the reverse method of StringBuffer.
Implementation:
Java
// Java program to demonstrate conversion from
// String to StringBuffer and reverse of string
import java.lang.*;
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args)
{
String str = "Geeks";
// conversion from String object to StringBuffer
StringBuffer sbr = new StringBuffer(str);
// To reverse the string
sbr.reverse();
System.out.println(sbr);
}
}
Explanation:
- This program demonstrates how to convert a
String to a StringBuffer and then reverse the string. - The
StringBuffer object is created from the original string, and the reverse() method is called to reverse its contents. - Finally, the reversed string is printed.
Complexities:
- Time complexity: O(n), where n is the length of the string.
- Space complexity: O(n), due to the
StringBuffer that stores the string.
Method 7: Using Stack
The idea of stack is that we will be accessing only top element of a stack so it includes 2 steps as follows:
- push all the characters in stack.
- pop all the characters from stack and append to temp string.
Below is the implementation of the above approach.
Java
import java.util.*;
class GFG {
public static void main(String[] args) {
String s="Geeks For Geeks";
//initializing a stack of type char
Stack<Character> stack=new Stack<>();
for(char c:s.toCharArray())
{
//pushing all the characters
stack.push(c);
}
String temp="";
while(!stack.isEmpty())
{
//popping all the chars and appending to temp
temp+=stack.pop();
}
System.out.println("Reversed string is : "+temp);
}
}
OutputReversed string is : skeeG roF skeeG
Explanation:
- This program reverses a string using a stack. It first pushes each character of the string “Geeks For Geeks” onto the stack.
- And then pops each character off the stack, appending them to a new string in reverse order.
- Finally, the reversed string is printed.
Complexities:
- Time complexity: O(n), where n is the length of the string.
- Space complexity: O(n), due to the stack storing the characters.
Example:
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.Scanner;
class GFG {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String Str = scanner.nextLine();
char[] arr = Str.toCharArray();
String rev = "";
for(int i = Str.length() - 1; i >= 0; i--)
{
rev = rev + Str.charAt(i);
}
System.out.println(rev);
}
}
Explanation:
- In the above code, we are essentially reading a String from the user before starting an iteration loop to create a new, inverted String.
- The “charAt” function of the String class is used to retrieve each character of the original String individually from the end, and the “+” operator is used to concatenate them into a new String.
Summary of Methods:
- For Loop: Simple and easy to understand.
- StringBuilder/StringBuffer: Efficient and concise with built-in
reverse() methods. - Character Array: Manual control over the reversal process.
- Stack: Suitable when the LIFO principle is required.
- ArrayList and Collections.reverse(): Useful for list manipulations.
- getBytes(): Works directly with byte arrays for low-level manipulation.
Understanding these various methods enables you to choose the best approach for your specific use case, ensuring optimal performance and code clarity.
Related Article: Different methods to reverse a string in C/C++