Reverse a String in Java (original) (raw)
Last Updated : 27 Mar, 2025
In Java, reversing a string means **reordering the string characters from the last to the first position. Reversing a string is a common task in many Java applications and can be achieved using different approaches. In this article, we will discuss multiple approaches to reverse a string in Java with examples, their advantages, and when to use them.
The for loop is a simple, straightforward approach to **reverse a string in Java that offers full control over the reversal process without relying on additional classes.
**Example: This example demonstrates reversing a string by iterating through each character and adding it to the front of a new string.
Java `
// Java Program to Reverse a String // Using for loop import java.io.*; import java.util.Scanner;
class GFG { public static void main(String[] args) {
String s = "Geeks";
String r = "";
char ch;
for (int i = 0; i < s.length(); i++) {
// extracts each character
ch = s.charAt(i);
// adds each character in
// front of the existing string
r = ch + r;
}
System.out.println(r);
}
}
`
Table of Content
Methods to Reverse a String in Java
There are several ways to reverse a string in Java. Below are the most common methods:
**1. Using getBytes()
The getBytes() method is used for converting the input string into bytes[]. Below are the steps to convert 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.
**Example: This example demonstrates reversing a string by converting it into a byte array and then rearranging the bytes in reverse order.
Java `
// Java program to Reverse String // Using ByteArray 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));
}
}
`
**2. Using StringBuilder.reverse() method
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.
**Example: This Java program demonstrates reversing a string using **the StringBuilder class and its reverse() method.
Java `
// Java program to Reverse String // Using StringBuilder 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);
}
}
`
**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.
**Example: This example demonstrates reversing a string by **converting it to a character array and printing the characters in reverse order.
Java `
// Java program to Reverse a String by // Converting string to characters 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]);
}
}
`
**4. Using Collections.reverse() method
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.
**Example: This example demonstrates reversing a string by **converting it to a character array, storing it in an ArrayList, and using Collections.reverse() with a ListIterator to print the reversed string.
Java `
// Java program to Reverse a String // Using ListIterator 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());
}
}
`
**5. Using StringBuffer.reverse()
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.
**Example: This example demonstrates reversing a string **using the StringBuffer class and its reverse() method.
Java `
// Java program to Reverse the String // Using StringBuffer 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);
}
}
`
6. Using Stack
We can reverse the string by using stack, when we work with **Last-In-First-Out (LIFO) logic that 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.
**Example: This example demonstrates reversing a string by pushing its characters onto a stack and popping them off to form the reversed string.
Java `
// Java program to reverse a string using Stack 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);
}
}
`
When to Use Which Method
- **For Loop: For simplicity and complete manual control over the reversal process.
- **getBytes(): When dealing with byte-level manipulations or encoding.
- **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.
**Reversing String by Taking Input from the User
In the below code, we are essentially reading a String from the user before starting an iteration loop to create a new, inverted String. The charAt() method 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.
**Example: This Java program demonstrates reversing a user-input string by iterating through it in reverse order and appending each character to a StringBuilder.
Java `
// Java Program to Reverse User Input String import java.io.*; import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Check if there is a line to read
if (sc.hasNextLine()) {
// Taking string from user
String s = sc.nextLine();
// Using StringBuilder to store
// the reversed string
StringBuilder res = new StringBuilder();
// Traversing from the end to start
for (int i = s.length() - 1; i >= 0; i--) {
// Adding element to the StringBuilder
res.append(s.charAt(i));
}
// Printing the reversed string
System.out.println(res.toString());
} else {
System.out.println("No input provided.");
}
sc.close(); // Close the scanner to avoid resource leak
}
}
`
**Note: When the user will provide the input, the program will reverse the string and will print the reversed output.