Reverse a String in Java
In Java, reversing a string means rearranging its characters from last to first. It’s a common programming task used in algorithms, data processing, and interviews. There are several ways to reverse a string in Java, from using loops to built-in methods.
1. Using a For Loop
The for loop is the most basic and manual approach. It provides complete control over the reversal process without using additional classes.
class GFG{
public static void main(String[] args){
String s = "Geeks";
String r = "";
for (int i = 0; i < s.length(); i++){
// prepend each character
r = s.charAt(i) + r;
}
System.out.println(r);
}
}
Output
skeeG
Explanation: Each character of the string is appended in reverse order to a new string r, resulting in the reversed output.
2. Using StringBuilder.reverse()
StringBuilder provides a built-in reverse() method, making string reversal quick and efficient.
import java.io.*;
class Main{
public static void main(String[] args){
String s = "Geeks";
// Object Initialised
StringBuilder res = new StringBuilder();
// Appending elements of s in res
res.append(s);
// reverse StringBuilder res
res.reverse();
// print reversed String
System.out.println(res);
}
}
Output
skeeG
Explanation: StringBuilder objects are mutable, and their reverse() method reverses the content in-place, which is faster than manual looping.
3. Using Character Array
We can use character array to reverse a string. Follow Steps mentioned below:
- 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.
import java.io.*;
class Main{
public static void main(String[] args){
String s = "Geeks";
// Using toCharArray to copy elements
char[] arr = s.toCharArray();
for (int i = arr.length - 1; i >= 0; i--)
System.out.print(arr[i]);
}
}
Output
skeeG
Explanation: The string is converted into a char[] array, and characters are printed in reverse order using a simple loop.
4. Using Collections.reverse()
The Collections.reverse() method can be used when dealing with lists. We can convert a string to a list of characters, reverse it, and print it back.
import java.util.*;
class Main {
public static void main(String[] args){
String s = "Geeks";
// Copying elements to Character Array
char[] arr = s.toCharArray();
// Creating new ArrayList
List<Character> l = new ArrayList<>();
// Adding char elements to ArrayList
for (char c : arr)
l.add(c);
// Reversing the ArrayList
Collections.reverse(l);
// Using ListIterator
ListIterator it = l.listIterator();
while (it.hasNext())
System.out.print(it.next());
}
}
Output
skeeG
Explanation: Characters are stored in a list and reversed using Collections.reverse(). This approach is helpful when you’re already working with Java collections.
5. Using StringBuffer.reverse()
StringBuffer is similar to StringBuilder but thread-safe. It also provides the reverse() method.
import java.io.*;
public class Main{
public static void main(String[] args){
String s = "Geeks";
// Conversion from String object
// To StringBuffer
StringBuffer sbf = new StringBuffer(s);
// Reverse String
sbf.reverse();
System.out.println(sbf);
}
}
Output
skeeG
Explanation: StringBuffer is synchronized, so it’s a good choice for multithreaded environments.
6. Using a Stack
The stack approach uses the Last-In-First-Out (LIFO) principle to reverse characters.
import java.util.*;
class Main{
public static void main(String[] args){
String str = "Geeks";
//initializing a stack of type char
Stack<Character> s = new Stack<>();
for(char c : str.toCharArray()){
//pushing all the characters
s.push(c);
}
String res="";
while(!s.isEmpty()){
//popping all the chars and appending to temp
res+=s.pop();
}
System.out.println(res);
}
}
Output
skeeG
Explanation: Each character is pushed onto the stack and then popped out, reversing the order naturally.
7. Using getBytes()
This method works at the byte level and is useful for encoding or low-level string manipulation.
import java.io.*;
class Main {
public static void main(String[] args) {
String s = "Geeks";
// getBytes() method to convert string
// into bytes[].
byte[] arr = s.getBytes();
byte[] res = new byte[arr.length];
// Store reult in reverse order into the
// res byte[]
for (int i = 0; i < arr.length; i++)
res[i] = arr[arr.length - i - 1];
System.out.println(new String(res));
}
}
Output
skeeG
Explanation: The string is converted to bytes, reversed, and then reconstructed into a new String.
When to Use Which Method
- For Loop: For simplicity and complete manual control over the reversal process.
- StringBuilder/StringBuffer: Efficient and concise with built-in
reverse()methods. - Character Array: When working with individual characters or for manual control.
- Collections.reverse(): When already working with lists or collections.
- Stack: When following the LIFO principle or using stacks in the algorithm.
- getBytes(): When dealing with byte-level manipulations or encoding.