Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Program to Reverse A String In Java

Last Updated on September 22, 2023 by Mayank Dham

In this article, we will deep dive and discuss how to reverse a string in Java. Reversing a string is a common coding exercise that not only demonstrates your understanding of fundamental programming concepts but also showcases your problem-solving skills. In the world of programming, manipulating strings efficiently is essential, and being able to reverse a string is a handy technique. In this article, we will dive into different approaches for reversing a string in Java. Whether you’re a beginner looking to understand the basics or an experienced developer seeking a refresher, this article will guide you through various methods to achieve this task.

Consider the following example –
If the input string is “HELLO”, the reverse of it will be “OLLEH”. The provided string is reversed but not a palindrome.

"Aibohphobia," which ironically is a dread of palindromes, is a nice illustration of a string palindrome.

Different Ways to Reverse a String in Java

We’ll examine 8 distinct Java techniques for reversing strings. Since strings are immutable, or cannot be changed fundamentally, we always make a copy of the supplied string before attempting to reverse it.

For ease of implementation regardless of the use case you are working with, each technique is coded and described in the form of a function.

1. By using toCharArray()

Using the toCharArray() function is one way to reverse a string in Java.

public static String reverse(String str) {
  String rev = "";
  char[] finalarray = str.toCharArray();
  for (int i = finalarray.length - 1; i >= 0; i--)
    rev += finalarray[i];
  return rev;
}
//Sample Input- "PrepBytes"
//Sample Output-"setyBperP"

Output

setyBperP

Let’s try to understand the above code –

  • reverse() is a user-defined function that we have developed.
  • The toCharArray() is the function used to convert the string into a sequence of characters.
  • After that, using the length() function, we are finding the length of the character array.
  • We are printing the reverse of the character array using a for a loop.
  • The time complexity to reverse a string in Java is O(N).
  • The space complexity to reverse a string in Java is O(N).

2. By using StringBuilder

StringBuilder is a class in Java. It has an in-built method reverse(). The characters in the string are reversed using this function.

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes
{
    public static String reverse(String str) {
        StringBuilder obj = new StringBuilder();
        obj.append(str);
        obj.reverse();
        return obj.toString();
    }
    
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "PrepBytes";
        String result = reverse(s);
        System.out.println(result);
    }
}

Output

setyBperP
  • StringBuilder objects are mutable. Therefore, we have produced an object of the StringBuilder class named "obj".
  • The input string "str" is then appended using the append() technique.
  • The reverse() method is then called using obj and the result is returned.
  • The time complexity to reverse a string in Java will be O(N).
  • The space complexity to reverse a string in Java is O(N).

3. By using While Loop

Using the while loop is one of the easiest ways to reverse a string in Java. This method involves adding each character from the end to the beginning, one at a time, to a new string variable.

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes
{
    public static String reverse(String str) {
    String rev = "";
    int len = str.length();
    while (len > 0) {
        rev += str.charAt(len - 1);
        len--;
    }
    return rev;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "PrepBytes";
        String result = reverse(s);
        System.out.println(result);
    }
}

Output

setyBperP

Let’s try to understand the above code –

  • We have used the length() method to find the length of the input string “str”.
  • We run the while loop on the condition- length should be greater than zero.
  • Next, we print the string using the charAt() method, which returns the character at the specified index of the given string.
  • Lastly, we decrement the length variable “len”.
  • The time complexity to reverse a string in Java is O(N).
  • The space complexity to reverse a string in Java is O(N).

4. By using For Loop

For loops, similar to while loops, we can employ a similar strategy.

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes
{
    public static String reverse(String str) {
        String rev = "";
        int i = 0;
        int len = str.length();
            for (i = len; i > 0; i--) {
            rev += str.charAt(i - 1);
        }
        return rev;
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "PrepBytes";
        String result = reverse(s);
        System.out.println(result);
    }
}

Output

setyBperP
  • We use the length method to find the length of the input string str.
  • After that, we use the control variable i and run the loop backwards.
  • We then use the charAt() function to create the string in a reverse order which is then returned.
  • The time complexity to reverse a string in Java is O(N).
  • The space complexity to reverse a string in Java is O(N).

5. By converting string to bytes

The Java getBytes() function can also be used to reverse a string.

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes
{
    public static String reverse(String str) {
        byte[] strAsByte = str.getBytes();
        for (int l = 0, h = str.length() - 1; l < h; l++, h--) {
            byte temp = strAsByte[l];
            strAsByte[l] = strAsByte[h];
            strAsByte[h] = temp;
        }
        return new String(strAsByte);
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "PrepBytes";
        String result = reverse(s);
        System.out.println(result);
    }
}

Output

setyBperP
  • The input string str is transformed into Bytes using the getBytes() function.
  • The next step is to generate a fresh temporary byte array whose size should match the input string.
  • Using a for loop, we go over the entire length of the byte array.
  • With the help of a temp variable, we execute swapping inside the loop. The function eventually converts it back to a string and then returns the reversed string, strAsByte.
  • The time complexity to reverse a string in Java is O(N).
  • The spatial complexity to reverse a string in Java is O(N).

6. By using ArrayList objects

Let’s look at how to reverse a string using the ArrayList objects in Java –

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes
{
    public static String reverse(String str) {
        char[] strarray = str.toCharArray();
        List < Character > revString = new ArrayList < > ();
        for (char c: strarray)
            revString.add(c);
        Collections.reverse(revString);
        return revString.toString();
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "PrepBytes";
        String result = reverse(s);
        System.out.println(result);
    }
}

Output

setyBperP

Let’s talk about the code above and what it accomplishes now –

  • Using, toCharArray() method, the string is converted into a character array.
  • We add it to the ArrayList object.
  • Next, we use the Collections class in Java which also has an in-built reverse() function.
  • Thus, to reverse it, the ArrayList object revString is passed by this function. The reversed string is then returned.
  • The time complexity to reverse a string in Java is O(N).
  • The space complexity to reverse a string in Java is O(N).

7. By using StringBuffer

Java’s StringBuffer function allows us to effectively reverse a string.

The input string is first converted to a StringBuffer, and then the string is reversed using the built-in reverse() method.

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes
{
    public static String reverse(String str) {
        StringBuffer sb = new StringBuffer(str);
        sb.reverse();
        return sb.toString();
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "PrepBytes";
        String result = reverse(s);
        System.out.println(result);
    }
}

Output

setyBperP

In the above code, the time complexity to reverse a string in Java is O(N) and the space complexity to reverse a string in Java is O(N).

8. By using recursion

The definition of recursion is a function calling itself. To reverse a string in Java thus far, we have used looping structures. But writing a recursive function is another way we can accomplish this.
Therefore, we will write a function that will be used recursively in Java to reverse a string.

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes
{
    public static String reverse(String str) {
        if (str.length() == 0)
            return "";
        return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "PrepBytes";
        String result = reverse(s);
        System.out.println(result);
    }
}

Output

setyBperP
  • We have constructed "reverse" as a recursive function in the snippet of code above.
  • The function receives the input string as input.
  • As you can see, we effortlessly reversed the string in one line of code using the substring() technique. That is recursion’s attraction.
  • As we execute the same function iteratively for each character in the string, the time complexity to reverse a string in Java will be O(N^2).
  • The complexity of space to reverse a string in Java will be O(N^2). The function is kept in the call stack, which is why this is the case. As a result, each time the substring() method succeeds, a duplicate start and end index is returned, taking up additional space.
  • Recursion allows us to write shorter code whereas iteration results in repetitive blocks of code. It is more time complex than iteration structures, though. Recursion causes a new stack frame to be allocated, which is why this is the case. This causes it to process the recursive call stack frame in addition to the iterations, which slows it down.

Conclusion
Despite the fact that Java string objects are inherently immutable, we looked at a variety of manipulation techniques in this tutorial. In particular, we looked at the various methods for java program to reverse a string. We may accomplish this by either creating some logic to perform the string reversal or by using built-in functions like reverse(). The String class also includes a number of well-known string functions that can be used to trim, compare, convert, and other operations on strings. After considering the time and space constraints, we would advise using StringBuffer to reverse a string in java. It features the most advantageous complexity levels and a straightforward implementation.

FAQ Related to WAP reverse a string in Java

Q1: What is the most efficient way to reverse a string in Java?
The most efficient way to reverse a string is to convert it to a character array and then swap the characters from the beginning and end of the array. This approach has a time complexity of O(n/2) due to the swapping process.

Q2: Can I use the StringBuilder class to reverse a string in Java?
Yes, you can use the StringBuilder class to reverse a string efficiently. The StringBuilder offers a reverse() method that can reverse the characters of a string in-place.

Q3: How does the approach of converting to a character array work?
Converting a string to a character array allows you to manipulate individual characters directly. By swapping the characters from the beginning and end of the array and moving towards the center, you effectively reverse the string.

Q4: Is string reversal an important skill for programmers?
Yes, string reversal is a fundamental skill that highlights your understanding of string manipulation and basic programming concepts. It’s a common exercise in coding interviews and can be useful in various programming scenarios.

Q5: Can I reverse a string using recursion?
Yes, you can reverse a string using recursion by recursively swapping the first and last characters of the string until the entire string is reversed. However, this approach might not be as efficient as other methods due to the overhead of recursion.

Leave a Reply

Your email address will not be published. Required fields are marked *