CodeGym/Java Blog/Random/Different Ways to Reverse a String in Java

Different Ways to Reverse a String in Java

Published in the Random group
members
Strings in java can also be said as an array of characters. Strings in java are used for storing text/characters. In the java programming language, the strings are considered objects. In Java, strings are the objects of a predefined which is class named String. All the string variables are instances of the String class in java. Hence we can understand that the strings in java are not of the primitive types like the int or the char in other programming languages. In this article, we will read how to reverse a string in java the prerequisite for this is that u should know how to create a string in java, and basic concept of inbuilt string methods, and how to perform operations with the help of loops.

Scope of the article

- In this article, we will read about the various ways how to reverse a string in java. - We will also see some pre-built methods through which we can reverse a string in java. - We will also read about the time and space complexity of each reverse method in java. - There are several ways to reverse a string in Java, each with its advantages and disadvantages. In this article, we will explore some of the most commonly used methods for reversing a string in Java.

Introduction

Strings are immutable objects in java, strings are just a sequence of characters in java. Single lines strings in java are defined with single quotes while multiple lines strings in java are defined with triple quotes, java has several string methods available, but today in this article we will read about the different ways how to reverse a string in java. Java programming language is one of the most widely used programming languages in the world, and it is known for its simplicity and ease of use. One of the most common operations that programmers perform on strings is reversing them. In this article, we will discuss different ways to reverse a string in Java. First, let us read about the most common way that is using the for loop in java:

Reverse the string in java using the for loop:

This technique is one of the simplest ways to reverse a string in Java by using a for loop. We can iterate through the characters of the string from the end to the beginning, and add them to a new string variable. Here is an example of how to reverse a string using a for loop:
//in the above code we have reversed the string using a for loop in java
public class reverseofthestring {
  public static void main(String[] args) {

    String s1 = "java is fun";
      // we are creating the second string to store the reversed string and print it while iterating the for loop
    String s2 = "";

    for(int i = s1.length()-1; i>=0; i--)
    {
        // in the above line we have stored the reversed string by iterating the for loop from the last index and stored the value in the second string created s2.
      s2 = s2 + s1.charAt(i);
    }

    System.out.print("The reversed string of the '"+s1+"' is: " );
    System.out.println(s2);
  }
}
Output
The reversed string of the s1 is:nuf si avaj
In the above code, we have first taken the input of a string named s1 and created an empty string s2 and then iterated the for loop from the last index and then we have stored the value of each character in that string. Run the above code in your editor for a better and clear explanation. The time complexity of the above code is O(N), and as we have iterated over all the n elements the space complexity of the above code is O(N). Now let us read about the next process which is reversing the string using the string builder, so now let us read about it in detail:

Reversing the string using the string builder class

We can also reverse the string in Java by using the StringBuilder class. The StringBuilder class provides a reverse() method that can be used to reverse a string. The reverse() method of the Java StringBuilder class is used to replace this character sequence with the reverse of the sequence. The StringBuilder class in java does not have the toCharArray() method, while the String class does have the toCharArray() method. Now let us understand with the help of an example:
public class reverseusingbuilder {
    public static void main(String[] args) {
        StringBuilder s1 = new StringBuilder("abc");
        System.out.println("The original string1 is  = " + s1);
        StringBuilder s2 = new StringBuilder("cab");
        System.out.println("The original string2 is = " + s2);
         StringBuilder s3 = new StringBuilder("wer");
        System. out.println("The original string3 is = " + s3);
        // reversing of stringbuilder
        System.out.println("The reverse of the string is reverse1 = " + s1.reverse());
        System.out.println("The reverse of the string2 is reverse2 = " + s2.reverse());
         System.out.println("The reverse of the string3 is reverse2 = " + s3.reverse());
    }
}
Output
The original string1 is  = abc
The original string2 is  =cab
The original string3 is  =wer
The reversed string1 is  = cba
The reversed string2 is  = bac
The reversed string3 is  =rew
In this method, we can see that using the inbuilt string builder class we have reversed the string. This method is very efficient, as it only requires a single pass through the string. However, it does require the creation of a new StringBuilder object, which can add some overhead. This method is relatively simple and easy to understand, but it can be less efficient than other methods, as it requires multiple passes through the string and the creation of a new string for each character. Run the above code in your editor for a better and clear explanation. Now let us see another way to reverse the string using the recursion technique:

Reverse the string using recursion

Recursion is a technique in which a function calls itself. We can use recursion to reverse a string by breaking it down into smaller substrings. Recursion in java is a process in which a method calls itself continuously. To reverse the string in java using recursion first we have to remove the first character from the string and then append that character at the end of the string and then we have to repeat the above step until the input string becomes empty. Now let us understand this with the help of an example:
public class reverse string
{
//in this line we are writing the recursive function to reverse a string
public String reverse string(String s1)
{
//first we will check if the string is empty or not
if(s1.isEmpty())
{
System. out.println("String is empty.")
//if the above condition is true then it returns the same string as if the string is empty itself then we cannot reverse the string
return s1;
}
else
{
return reverseString(s1.substring(1))+s1.charAt(0);
}
}
public static void main(String[] args)
{
reversestring q1 = new reversestring();
String res1 = q1.reverseString("JAVA IS FUN");
String res2 = q1.reverseString("STRINGS OBJECTS JAVA");
String res3 = q1.reverseString("IMMUTABLE CLASS OBJECTS");
System.out.println(res1);
System.out.println(res2);
System.out.println(res3);
}
}
Output
NUF SI AVAJ
AVAJ STCEJBO SGNIRTS
STCEJBO SSALC ELBATUMMI
Hence we can see that in the above that using recursion we have reversed the string we have first checked whether the string is empty or not if the string will be empty then there will be no characters that can be reversed. This method can be more efficient than the for-loop method, as it only requires a single pass through the string. However, it can also be more complex and harder to understand, as it involves the use of recursion. Run the above code in your editor for a better and clear explanation. Let us see another example of how to reverse a string using recursion in java:
public static String reverseusingrecursion(String s1) {
    if (s1.length() == 1) {
        return s1;
    }
    //We have applied recursion in this line
    return s1.charAt(s1.length() - 1) + reverseUsingRecursion(s1.substring(0, s1.length() - 1));
}
Now let us read about another way to reverse a string in java that is using the array:

Reverse a string in java using an array

We can also reverse a string by converting it to a character array, changing the array, and then converting it back to a string. First, we have to create an empty character array of the same size as that of the given string then we have to fill the character array backward with characters of the given string, and then finally we have to convert the character array into the string using the copy method and return it. Now let us understand this with the help of an example:
public class Main
{
    // In this Method of conversion we have to reverse a string in Java using a character array
    public static String reverse(String s1)
    {
        // we have to check if the string is empty or not and return if the string is null or empty
        if (s1 == null || s1.equals("")) {
            return s1;
        }
 // if it is equal to empty then we will simply print the string and break it.
        // else we will find the string length
        int len = str.length();

        // and then we have to create a character array of the same size as that of the string to store the value after reversing
        char[] new_arr = new char[n];

        // and by iterating the loop backward we have to fill the character array backward with characters in the string
        for (int i = 0; i < len; i++) {
            new_arr[len - i - 1] = str.charAt(i);
        }

        // and in the final step after reversing we have to convert the character array to string and return it
        to return String.copy value of(new_arr);
    }

    public static void main(String[] args)
    {
        // taking a string input for reverse
        String s1 = "JAVA IS FUN";

        // In this line we are calling the reverse function and reversing the string
        str = reverse(str);

        System.out.println("The reversed string is " + s1);
    }
}
Output
NUF SI AVA
In this method we have to reverse the string to a character array we know so firstly we will check if the string is empty or not and return if the string is null or empty if it is equal to empty then we will simply print the string and break else we will find the string length and then we have to create a character array of the same size as that of string to store the value after reversing and by iterating the loop backward we have to fill the character array backward with characters in the string and in the final step after reversing we have to convert the character array to string and return it. Run the above code in your editor for a better and clear explanation. Now let us read about the next step we can also reverse the string in java using the Stream API. So now let us read about them in detail with the help of some examples:

Reverse a string in java using the Stream API:

Java 8 introduced the Stream API that can be used to perform functional-style operations on collections. We can use the Stream API to reverse a string by converting it to a stream of characters, reversing the stream, and then converting it back to a string. We can reverse a string in java using various streams and collectors first we have to input a string and then use a Map on the entire String into a StringBuilder object and at the same time reverse it using the reverse() method of the StringBuilder class and then Finally, collecting the reversed String using the Stream. collect() method and Collectors. joining() method we will print both original/reversed Strings along with their length. Now let us understand this with the help of an example:
public static String reverseUsingStream(String str) {
    return str. chars()
              .mapToObj(c -> (char) c)
              .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
              .reverse()
              .toString();
}
In this example, we have reversed the string in java using the java streams and collectors. Run the above code in your editor for a better and clear explanation. Now let us see how we can reverse the string using the stack. Now let us read about it in details with the help of an example:

Reverse the string using the stack

There is another way to reverse a string in Java which is by using a stack. The idea is to push each character of the input string to the stack and then pop characters from the stack to get the reversed string. Now let us read more about it in detail with the help of an example:
public static String reverse string(String input) {
    Stack<character> stack = new Stack<>();
    for (int i = 0; i < input.length(); i++) {
        stack.push(input.charAt(i));
    }
    StringBuilder sb = new StringBuilder();
    while (!stack.isEmpty()) {
        sb.append(stack.pop());
    }
    return sb.toString();
}

</character>
In the above example, we first created an empty stack and then reversed the string and inserted the elements inside the stack. This method is simple, easy to understand, and efficient. Run the above code in your editor for a better and clear explanation.

Conclusion

The first method is by using the StringBuilder class, which has a built-in reverse() method that returns a new string that is the reverse of the original string. The second method is using a for loop, where we convert the original string to a char array and iterate through the array in reverse order, assigning the corresponding characters to a new char array, and finally creating a new string using that char array. The third method is using recursion, where we call a recursive function and solve the problem by concatenating the first character of the string with the reversed substring of the remaining characters. The fourth method is by using an array to reverse a string in java. In the fifth method, we used the stream API and the java collector to reverse the string and, In the last method we used the stack to reverse the string in java. Each of these methods has its advantages and disadvantages, and the choice of method depends on the specific requirements of the problem and the programmer’s preference. Overall, these methods demonstrate the flexibility and versatility of Java in string manipulation.
Comments (1)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Anonymous #11234130
Level 15 , Finland
1 February 2023, 05:58
Nice topic, but there were so many errors in the syntax and code formatting was off so I kind of lost focus