Program to Reverse A String In Java

In this article, we will deep dive and discuss how to reverse a string in Java. A string is a group of characters that serves as an object in Java. It is one of the most often used data structures after arrays. A string is essentially a character array.

In this article, we’ll look at various Java methods for reversing strings. If you wish to determine whether a string is a palindrome or not, a string reversal may be useful. A string that is identical when read from right to left and left to right is referred to as a palindrome.

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.

Leave a Reply

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