Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
How To Reverse A String In Java: Explained

How To Reverse A String In Java: Explained

10 Sep 2024
Beginner
461 Views
14 min read
Learn with an interactive course and practical hands-on labs

Free Java Foundation Course

Reverse A String In Java

To reverse a string in Java word by word, you can split the string into an array of words using the split() method, reverse the order of the words in the array, and then join them back into a single string using StringBuilder or String. join(). This process allows you to maintain the original words' order while reversing their sequence in the string.

In this Java tutorial, We are gonna see how to reverse a string in Java word by word, so bring yourself to the present and understand this article carefully.

Gain the skills needed for top developer roles by joining our Java Full Stack Developer Course Training program.

Understanding Strings in Java

  • Strings are objects in Java that represent character sequences.
  • They cannot have their content changed once they are created since they are immutable.
  • Java has two mutable options, StringBuilder and StringBuffer, for effective string manipulation.
  • For understanding strings there are two main points to be considered first they are as follows.

Understanding Strings in Java

1. Strings' immutability

Because Java allows strings to be immutable, once a string object is created, its contents cannot be changed. A new string object is actually created by any operation that seems to modify an existing string.

2. Overview of StringBuffer and StringBuilder

In Java, String has mutable counterparts called StringBuilder and StringBuffer. They are effective for operations like concatenation and reverse because they offer ways to change strings without generating new objects.

Methods to Reverse a String in Java

In Java programming, reversing a string is a frequently used action that can be accomplished in various ways.

Here are several Java methods for reversing a string, along with corresponding code samples with output.

  1. Using the StringBuilder Class and Its Description
  2. Using Recursion
  3. Using Iterative Approach
  4. Using Stack
  5. Using Collections Framework

1 Using the StringBuilder Class

Java's StringBuilder class is a flexible tool for constructing changeable strings. It offers a number of ways to work with string content, one of which is an inbuilt method named reverse() that allows you to reverse a string.

How To for Reversing a String Making Use of StringBuilder

  • Initialize a StringBuilder object with the original string after creating it.
  • Make use of the StringBuilder object's reverse() method.
  • Return the StringBuilder object to its original string form.

Example

public class ReverseStringExample {
    public static void main(String[] args) {
        String original = "Welcome to Scholarhat";
        StringBuilder sb = new StringBuilder(original);
        String reversed = sb.reverse().toString();
        System.out.println("Reversed String: " + reversed);
    }
}

Output

Reversed String: tahralohcS ot emocleW

2. Using Recursion

Java's Recursion Concept
Programming recursion is the process by which a method calls itself to address an issue. Recursion can be used to reverse a string by dissecting it into smaller pieces and rearranging the parts to make the combination.

How to Reversing a String Making Use of Recursion-Based String Reversal

  • Define a recursive function that accepts the string as an input along with its length.
  • Return the string if its length is one or less.
  • If not, concatenate the first character at the end and run the procedure recursively with the substring.
Read More: Recursion in Data Structures

Example

public class ReverseStringExample {
    public static void main(String[] args) {
        String original = "Welcome to Scholarhat";
        String reversed = reverseString(original);
        System.out.println("Reversed String: " + reversed);
    }
    public static String reverseString(String str) {
        if (str.isEmpty()) {
            return str;
        }
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}

Output

Reversed String: tahralohcS ot emocleW

3. Using Iterative Approach

The string is reversed using a loop in the iterative method. You can create a new string containing characters in reverse order by iterating through the string from the beginning to the finish.
How to Reversing a String Making Use of a Loop to Reverse a String
  • Set up a blank string or StringBuilder object from scratch.
  • Reverse the order of the original string's loops.
  • To the newly created string or StringBuilder object, append each character.

Example

public class ReverseStringExample {
    public static void main(String[] args) {
        String original = "Welcome to Scholarhat";
        String reversed = "";
        for (int i = original.length() - 1; i >= 0; i--) {
            reversed += original.charAt(i);
        }
        System.out.println("Reversed String: " + reversed);
    }
}

Output

Reversed String: tahralohcS ot emocleW

4. Using Stack

Overview of Stack Data Structure
A stack is a data structure that is arranged last-in, first-out (LIFO), with elements being added and discarded starting at the top. Because the letters can be loaded onto the stack and then popped off in the opposite order, this trait makes it helpful for reversing a string.
How to Reversing a String Making Use of Stack
  • Place each character in the string into the corresponding stack.
  • Add each character to a new string or StringBuilder object by popping it off the stack.

Example

import java.util.Stack;

public class ReverseStringExample {
    public static void main(String[] args) {
        String original = "Welcome to Scholarhat";
        Stack stack = new Stack<>();
        for (char c : original.toCharArray()) {
            stack.push(c);
        }
        StringBuilder reversed = new StringBuilder();
        while (!stack.isEmpty()) {
            reversed.append(stack.pop());
        }
        System.out.println("Reversed String: " + reversed.toString());
    }
}

Output

Reversed String: tahralohcS ot emocleW

5. Using Collections Framework

Collection framework concept
The Java Collections Framework offers a utility class called Collections, which has a reverse() method that allows you to reverse the order of elements in a list. This can be used to reverse a string by first converting it to a list of characters, then reversing it, and finally converting it back to a string.
How to Reversing a String Using Collections.reverse():
  • Convert the string to a list of characters.
  • Use Collections.reverse() to reverse the list.
  • Convert the list back to a string.
Read More: Collection Framework in Java

Example


import java.util.*;

public class ReverseStringExample {
    public static void main(String[] args) {
        String original = "Welcome to Scholarhat";
        List charList = new ArrayList<>();
        for (char c : original.toCharArray()) {
            charList.add(c);
        }
        Collections.reverse(charList);
        StringBuilder reversed = new StringBuilder();
        for (char c : charList) {
            reversed.append(c);
        }
        System.out.println("Reversed String: " + reversed.toString());
    }
}

output

Reversed String: tahralohcS ot emocleW

3. Comparing the Effectiveness of Various Techniques

Time Complexity Study for Every Technique
1. StringBuilder: O(n) is the time complexity, where n is the string's length. It works well and is appropriate in most situations.
2. Recursion: While time complexity is O(n), there is also the overhead of many recursive calls, which, in the case of very big strings, may cause a stack overflow.
3. Iterative Method: If a standard string is used, there is an additional overhead of string concatenation, making the time complexity O(n). This can be lessened by using StringBuilder in the iterative process.
4. Stack: Although the time complexity is O(n), the space efficiency is lower since more room is needed for the stack.
5. Framework for Collections: Reversing the list has an O(n) time complexity, however converting a string to a list has a

Analysis of Space Complexity

  • StringBuilder: The reversed string has an O(n) space complexity.
  • Recursion: Because of the recursion stack, space complexity is O(n).
  • Iterative Approach: For the inverted string, the space complexity is O(n).
  • Stack: For both the stack and the inverted string, the space complexity is O(n).
  • Framework for Collections: For both the list and the inverted string, the space complexity is O(n).

Top Applications for Every Method

  • StringBuilder: Perfect for the majority of ordinary situations where simplicity and efficiency are needed.
  • Recursion: Ideally used in instructional settings or where the nature of the problem calls for a recursive solution.
  • Iterative Approach: Practical when you want a simple implementation and memory overhead is an issue.
  • Stack: Appropriate for handling issues or ideas pertaining to stacks.
  • Collections Framework: Useful in scenarios when you wish to make use of pre-existing tools and are already working with lists.
Every approach has advantages and disadvantages, and the best approach will rely on the particulars of the issue you're attempting to solve.
Conclusion
In Java, reversing a string is a typical programming task that can be approached in a variety of ways, depending on the situation. You can effectively reverse a string depending on your needs by understanding the fundamental ideas behind strings, such as their immutability, and making use of resources like StringBuilder, recursion, iterative loops, stacks, and the Collections framework. However, if you want to learn other Java concepts like this you can go with our Full Stack Java Developer Course

FAQs

To reverse a string in place, you need to convert it into a mutable data structure (like an array) first, perform the reversal, and then convert it back to a string

Reverse A String Using For Loop

Copy alphabetic characters from the given array to temp[]. Reverse temp[] using standard string reversal algorithm. Now traverse input string and temp in a single loop. Wherever there is an alphabetic character is input string, replace it with the current character of temp[].
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this