The Wayback Machine - https://web.archive.org/web/20240930174602/https://www.geeksforgeeks.org/reverse-a-string-in-java/
Open In App

Reverse a string in Java

Last Updated : 03 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

String Reverse

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);
    }
}

Output
Original 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));
    }
}

Output
skeeGrofskeeG

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);
    }
}

Output
skeeG rof skeeG

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]);
    }
}

Output
skeeGroFskeeG

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());
    }
}

Output
skeeG roF skeeG

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);
    }
}

Output
skeeG

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:

  1. push all the characters in stack.
  2. 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);
        
    }
}

Output
Reversed 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.

Reversing String by Taking Input from User

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);
        
    }
}

Output
0

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++



Previous Article
Next Article

Similar Reads

Create a new string by alternately combining the characters of two halves of the string in reverse
Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. Examples: Input : s = carbohydratesOutput : hsoebtraarcdy Input : s = sunshineOutput : sennuish Explanation: Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be
7 min read
Java Program to Reverse a String using Stack
The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first. Approach: Push the character one by one into the Stack of datatype character.Pop the character one by one from the Stack until the stack becomes empty.Add a popped element to the character
2 min read
Java Program to Swap Corner Words and Reverse Middle Characters of a String
Given a string containing n numbers of words. The task is to swap the corner words of the string and reverses all the middle characters of the string. Input: "Hello this is the GFG user" Output: "user GFG eth si siht Hello" Input: "Hello Bye" Output: "Bye Hello" Methods: Using the concept of ASCII valuesUsing the split() method Method 1: Using the
5 min read
Java Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Rec
4 min read
Reverse words in a given String in Java
Let's see an approach to reverse words of a given String in Java without using any of the String library function Examples: Input : "Welcome to geeksforgeeks" Output : "geeksforgeeks to Welcome" Input : "I love Java Programming" Output :"Programming Java love I" Prerequisite: Regular Expression in Java Java Code // Java Program to reverse a String
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Add index to characters and reverse the string
Given a string str, the task is to encrypt and reverse the string. The string is encrypted by adding every character of the string with it's index in the string i.e. if character'a' is at index 2 then the character in the updated string will be 'a' + 2 = 'c'. Since value of string may go beyond 256, do the addition under modulo 256.Examples: Input:
4 min read
Different Methods to Reverse a String in C++
Reversing a string is a common problem in programming that can be solved in various ways. This article will explore 6 different methods to reverse a string in C++, providing examples and explanations for each approach. 6 Different Ways to Reverse a String in C++Table of Content Reverse a String Using reverse() Function Reverse a String Using Revers
6 min read
Java Program for Reverse a linked list
Given a pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes. Examples: Input: Head of following linked list 1->2->3->4->NULLOutput: Linked list should be changed to, 4->3->2->1->NULL Input: Head of following linked list 1->2->3-
3 min read
Integer reverse() Method In Java
The java.lang.Integer.reverse() is an inbuilt method in Java and is used to return the reverse order of the bits in the two's complement binary representation of the specified int value. Syntax: public static int reverse(int a) Parameters: The parameter a is an integer value whose bits are to be reversed. Return Value: The method returns the value
2 min read
StringBuffer reverse() Method in Java with Examples
The Java.lang.StringBuffer.reverse() is an inbuilt method that is used to reverse the characters in the StringBuffer. The method causes this character sequence to be replaced by the reverse of the sequence. Syntax: public StringBuffer reverse() Parameters: NA Return Value: The method returns the StringBuffer after reversing the characters. Examples
2 min read
Reverse an ArrayList in Java using ListIterator
Assuming you have gone through arraylist in java and know about arraylist. This post contains different examples for reversing an arraylist which are given below:1. By writing our own function(Using additional space): reverseArrayList() method in RevArrayList class contains logic for reversing an arraylist with integer objects. This method takes an
6 min read
Reverse a LinkedList in Java
Assuming you have gone through LinkedList in java and know about linked list. This post contains different examples for reversing a linked list which are given below: 1. By writing our own function(Using additional space): reverseLinkedList() method contains logic for reversing string objects in a linked list. This method takes a linked list as a p
7 min read
StringBuilder reverse() in Java with Examples
The reverse() method of StringBuilder is used to reverse the characters in the StringBuilder. The method helps to this character sequence to be replaced by the reverse of the sequence. Syntax: public java.lang.AbstractStringBuilder reverse() Returns: This method returns StringBuilder object after reversing the characters. Below programs illustrate
1 min read
Reverse an array in Java
Given an array, the task is to reverse the given array in Java. Examples: Input : 1, 2, 3, 4, 5 Output :5, 4, 3, 2, 1 Input : 10, 20, 30, 40 Output : 40, 30, 20, 10 To know about the basics of Array, refer to Array Data Structure. Approaches There are numerous approaches to reverse an array in Java. These are: Using Temp arrayUsing SwappingUsing Co
4 min read
Reverse elements of a Parallel Stream in Java
Given a Parallel Stream in Java, the task is to reverse its elements. Examples: Input: Parallel Stream = {11, 22, 33, 44} Output: {44, 33, 22, 11} Input: Parallel Stream = {a, b, c, d} Output: {d, c, b, a} Below are the various ways to do so: Using Collectors class : Since Streams in Java don't store any elements, therefore, an intermediate collect
3 min read
How to create a TreeMap in reverse order in Java
By default TreeMap elements in Java are sorted in ascending order of keys. However, we can create the TreeMap in reverse order using Collections.reverseOrder() method in Java and display the elements in descending order of keys. The Collections.reverseOrderS() method in Java returns a Comparator that imposes reverse order of a passed Comparator obj
2 min read
Java Guava | Lists.reverse() method with Examples
Guava's Lists.reverse() method accepts a list as a parameter and returns a reversed view of the list passed as the parameter. If the specified list is random access, then the returned list is also random-access. For example: Lists.reverse(Arrays.asList(1, 2, 3)) returns a list containing 3, 2, 1. Syntax: public static <T> List<T> revers
2 min read
Evaluate the Value of an Arithmetic Expression in Reverse Polish Notation in Java
Reverse Polish 'Notation is postfix notation which in terms of mathematical notion signifies operators following operands. Let's take a problem statement to implement RPN Problem Statement: The task is to find the value of the arithmetic expression present in the array using valid operators like +, -, *, /. Each operand may be an integer or another
11 min read
Java Program to Reverse a Number and find the Sum of its Digits Using do-while Loop
Problem Statement: The number is supposed to be entered by the user be it any random number lying within the primitive data-type holding the number. First, the number needs to be reversed. Secondary the sum of the number is to be calculated with the constraint to use a do-while loop. do-while loop: Now the user sometimes does get confused between a
6 min read
Java Program to Reverse a Sentence Using Recursion
A sentence is a sequence of characters separated by some delimiter. This sequence of characters starts at the 0th index and the last index is at len(string)-1. By reversing the string, we interchange the characters starting at 0th index and place them from the end. The first character becomes the last, the second becomes the second last, and so on.
2 min read
Reverse Number Program in Java
In Java, reversing a number means that the digit at the first position should be swapped with the last digit, the second digit will be swapped with the second last digit, and so on till the middle element. Note: Leading zeros will not be considered after reversing (i.e, After reversing 100 will become 001 ≈ 1). Algorithm for Reversing a Number in J
3 min read
Priority Queue in Reverse Order in Java
A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap.
4 min read
How to Iterate LinkedHashMap in Reverse Order in Java?
The LinkedHashMap is used to maintain an order of elements inserted into it. It provides where the elements can be accessed in their insertion order. A LinkedHashMap contains values based on the key. It implements the Map interface and extends the HashMap class. It contains only unique elements or mappings. Syntax of Linkedhashmap public class Link
6 min read
Java Program to Traverse Through ArrayList in Reverse Direction
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java just as Vector in C++. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. The task is to insert an element in ArrayList and then Reverse it or say re
4 min read
Iterate List in Reverse Order in Java
The List interface provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Example Input: ["geeks", "for", "Geeks"] Output: ["Geeks", "for", "
3 min read
Iterate TreeMap in Reverse Order in Java
The TreeMap in Java is used to implement the Map interface and NavigableMap along with the AbstractMap Class. The TreeMap is sorted according to the natural ordering of its keys. There are three simple ways to iterate TreeMap in reverse order in Java: Using the reverseOrder() methodUsing the descendingKeySet() methodUsing the descendingMap() method
3 min read
Reverse Order of All Elements of Java Vector
Vector class Implements a dynamic array means it can shrink and expand its size as required just likely having the same operations like that in the arrays. Don't confuse it with ArrayList as there is a thin line between vector and ArrayList, where the vector is synchronized rest the insertion order remains the same in both of them. Vector is presen
4 min read
Java Program to Reverse a List
Reversing a list means after reversing the list, the first element should be swapped with the last element, the second element should be swapped with the second last element, and so on till the middle element and the resultant list is the reversed list. Example: Input: "PLATFORM", "LEARNING", "BEST", "THE", "IS", "GFG" Output: Reverse order of give
3 min read
Iterate a LinkedList in Reverse Order in Java
For traversing a linked list in reverse order we can use Descending Iterator or List Iterator 1. Descending Iterator Syntax: LinkedList<String> linkedlist = new LinkedList<>(); Iterator<String> listIterator = linkedlist.descendingIterator(); Returns: Descending Iterator returns the Iterator that points to the end of the linked lis
2 min read