How To Reverse A String In Java: Explained

How To Reverse A String In Java: Explained

10 Sep 2024
Beginner
159 Views
14 min read
Learn via Video Course & by Doing Hands-on Labs

Java Online Course Free with Certificate (2024)

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

Q1. How do you reverse a given string in place?

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

Q2. How to reverse a string without function?

Reverse A String Using For Loop

Q3. How do you reverse only alphabets in Java?

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

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingSep 21SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 21SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Software Architecture and Design TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
.NET Solution Architect Certification TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification TrainingOct 06SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core ProjectOct 13SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this