Reversing a String

A string denotes a sequence of characters considered an object in Java. In this language, there are multiple operations that you can carry out on the String object. One of the most general operations on a string object is String Reverse, which we will tackle in this article. Journey along with us as we show you a few approaches to Reverse a String in Java.


We all know that strings are immutable in Java. If you have no idea what an immutable object is, its internal state remains constant after being wholly created, which means no modification. As such, we cannot reverse a String by modifying it. For that reason, we need to create another String. As we earlier said, a string is reversed in several ways. Here are some that we will take you through in this article.

  • String Reverse using Reverse Iterative Approach
  • String Reverse using recursion
  • Reverse the letters present in the String
  • String Reversal using String Buffer/String Builder Approach
  • Using Stack
  • Using Character array
  • Using Character array and swap()
  • Using + (string concatenation) operator
  • Using Unicode Right-to-left override (RLO) character
  • Using a Byte Array
  • Using substring() method

Let us explore each of these approaches, starting with just how to reverse a string in Java using Reverse Iterative Approach.


Reversing a String Using Reverse Iteration

You will first convert the given String to Character Array using the CharArray() function in this method or approach. After that, iterate the given array in the reverse order as displayed below:

import java.util.List;
import java.util.Collections;
import java.util.ArrayList;
import java.util.ListIterator;
 
class Main
{
// Java's Method for reversing a string
Collections.reverse()
    public static String reverseString(String new_str)
    {
// base case: if string is empty or the string is null
        if (new_str == null || new_str.equals("")) {
            return new_str;
        }
 
// initialize an empty characters list
List new_list = new ArrayList();
 
// loop through the given string and push all characters into the new_list
        for (char new_char: str.toCharArray()) {
            new_list.add(new_char);
        }
 
// using java.util.Collections to reverse a list with //reverse()
        Collections.reverse(new_list);
 
// conversion of ArrayList into string using StringBuilder
        StringBuilder str_builder = new StringBuilder(list.size());
        for (Character new_char: list) {
            str_builder.append(new_cha);
        }
 
        return str_builder.toString();
    }
 
    public static void main(String[] args)
    {
        String new_str = "codeunderscored";
 
        // String is immutable
        new_str = reverse(new_str);
 
        System.out.println("Reversed strings is: " + new_str);
    }
}

The reversed string is: derocsrednuedoc

We hope you can now comprehend how to use the reverse iteration to approach a String in this programming language with the above sample. With that, let us proceed further and look at the second approach.

String Reverse using recursion

Recursion is nothing much than a function that ideally calls itself. We will write a program that reverses the String by calling itself recursively in this approach. Let us take a look at the program and check how it works:

class StringReversal
{
	static int j = 0;

	//  reversing a string using recursive approach in Java using a static variable
	private static void reverseString(char[] new_str, int n)
	{
		// after reaching the end of string
		if (n == new_str.length) {
			return;
		}

		// recur for the next character
		reverse(str, n + 1);

		if (i <= n)
		{
			char temp_val = new_str[k];
			new_str[n] = new_str[i];
			new_str[j++] = temp_val;
		}
	}

	public static String reverseString(String new_str)
	{
		// base case: string is either empty or it is null
		if (new_str == null || str.equals("")) {
			return new_str;
		}

		// convert string into a character array
		char[] A = str.toCharArray();

		// reverse character array
		reverse(A, 0);

		// convert character array into the string
		return String.copyValueOf(A);
	}

	public static void main(String[] args)
	{
		String str = "codeunderscored";

		// string is immutable
		str = reverseString(str);

		System.out.println("Reversed string is: " + str);
	}
}


The reversed string is: derocsrednuedoc

You should note that in the above program, we created the object for the class StringRecursion r. Then, we read the entered String using the sc.nextLine() command and stored it in the String variable str. In the end, we called the reverse method as r.reverseString(str). Having this in mind lets us push the article further and look at the following method of reversing strings.

String Reversal using String Buffer/String Builder Approach

StringBuffer and StringBuilder encompass an inbuilt method reverse() used to reverse the characters in the StringBuffer. This method substitutes the character sequence in the reverse order. Take a look at the sample below displaying how to reverse a String using an inbuilt method of the StringBuffer class.

class StringReversalUsingStringBuilder
{
	// Reversing a string using `StringBuilder` in Java
	public static String reverseString(String new_str) {
		return new StringBuilder(new_str).reverse().toString();
	}

	public static void main(String[] args)
	{
		String str = "I love codeunderscored";

		// Note that string is immutable in Java
		str = reverse(str);

		System.out.println("Reversed string is: " + str);
	}
}

The reversed string is derocsrednuedoc evol I

It is all there is on the StringBuilder approach class. We can alternatively take you through using a StringBuffer class reverse() method just like StringBuilder. Let us get going.

First, take a look at the program written below:

class usingStringBuilder
{
	// Reversing a string in Java using `StringBuffer`
	public static String reverseString(String new_str) {
		return new StringBuffer(new_str).reverse().toString();
	}

	public static void main(String[] args)
	{
		String str = "I love codeunderscored";

		// Note that string is immutable in Java
		str = reverseString(str);

		System.out.println("Reversed string is: " + str);
	}
}

The reversed string is derocsrednuedoc evol I

Note that you should receive the same output as the one from the StringBuilder class when you execute the program. Another point to remember is that you can either reverse as String using StringBuffer reverseString() as displayed in the above code, or on the other flip of the coin, you can use the code logic as shown below:

StringBuffer sb =new StringBuffer("Javacodeunderscored ");
System.out.println(sb.reverse());

Ideally, both StringBuilder and StringBuffer contain a look-alike approach or reversing a String in Java. However, StringBuilder is preferred despite the similarities as it is not synchronized and is faster than StringBuffer.

Using stack

This section can use the Stack data structure to help reverse a string in Java. Here are the steps to accomplish this

Step 1: Create an empty stack of characters.

Step 2: Convert the given string into a character array using the String.toCharArray() method and push each character to fit into the stack.

Step 3: After that, remove characters from the stack until it is empty. Then assign them back to the character array. As stack follows FILO meaning (First in, Last Out) order, characters are inserted in the reverse order.

Step 4: Using the String.copyValueOf(char[]) command, convert the character array into a string, and return the created string.

Take a look at the sample shown below:

import java.util.Stack;

class usingCopyValueOf
{
	// Method to reverse a string in Java using a stack and character array
	public static String reverseString(String new_str)
	{
		// base case: the string is either empty or null
		if (new_str == null || new_str.equals("")) {
			return new_str;
		}

		// creation of an empty stack of characters
		Stack<Character> stack_char = new Stack<Character>();

		// pushing every character of the given string into the tack
		char[] new_ch = new_str.toCharArray();
		for (int i = 0; i < new_str.length(); i++) {
			stack_char.push(new_ch[i]);
		}

		// index starts from 0
		int n = 0;

		// popping stack characters' till it's empty
		while (!stack_char.isEmpty())
		{
			// assigning every popped character back to the character array
			new_ch[n++] = stack_char.pop();
		}

		// converting the character array into a string and return it
		return String.copyValueOf(new_ch);
	}

	public static void main(String[] args)
	{
		String str = "codeunderscored";

		str = reverse(str);		// string is immutable

		System.out.println("Reversed string is: " + str);
	}
}

The reversed string is: derocsrednuedoc

With that, let us take a look at the next method Using character array

Using character array

As we earlier said, you cannot make any change in the string object as a string in Java is immutable. Nonetheless, we can utilize an easily modifiable character array. Below are the steps to achieve this:

Step 1: Generate an empty character array of the same cardinality as the given string.
Step 2: Fill the character array backward with characters of the given string
Step 3: Finally, convert the character array into a string using this String.copyValueOf(char[]) command and return it.

Below is a demonstration of the above-given steps:

class convertUsingCopyValueOf
{
    // reversing a string in Java  with the help of a character array
    public static String reverseString(String new_str)
    {
        // return if the string is either empty or it is is null
        if (new_str == null || new_str.equals("")) {
            return new_str;
        }
 
        // string's length
        int n = new_str.length();
 
        // create a character array of equivalent size to that of the string
        char[] temp_char = new char[n];
 
        // filling character array backward with string's characters
        for (int i = 0; i < n; i++) {
            temp_char[n - i - 1] = new_str.charAt(i);
        }
 
        // converting character array to string and returning it
        return String.copyValueOf(temp_char);
    }
 
    public static void main(String[] args)
    {
        String str = "codeunderscored";
 
        // Strings are immutable in Java
        new_str = reverseString(new_str);
 
        System.out.println("Reversed sring is: " + str);
    }
}   


Using character array and swap() method

Here is another proficient method to reverse a string in Java using character array:

Step 1: Create a character array and modify it with a set of characters of a given string using String.toCharArray().
Step 2: Begin from the given string’s two endpoints, l and h. Then, execute the loop till the two mentioned points intersect (l <= h). In every loop iteration, swap values present indexes l and h and increment l and decrement h.
Step 3: At the end, convert the character array into string using String.copyValueOf(char[]) and return.


Below is a demonstration of the above explanation:

class convertCharacterArrayIntoString
{
	// reversing a string in Java using a character array
	public static String reverseString(String new_str)
	{
		// returns if the string's return either is null or empty
		if (new_str == null || new_str.equals("")) {
			return new_str;
		}

		// creating a character array and initializing it with the specified string
		char[] new_char = new_str.toCharArray();

		for (int l = 0, h = new_str.length() - 1; l < h; l++, h--)
		{
			// swap values at `l` and `h`
			char temp_val = new_char[l];
			new_char[l] = new_char[h];
			new_char[h] = temp_val;
		}

		// convert character array to string and return
		return String.copyValueOf(c);
	}

	public static void main(String[] args)
	{
		String str = "programming with codeunderscored";

		// String is immutable
		str = reverse(str);

		System.out.println("Reversed string is: " + str);
	}
}

The reversed string is: derocsrednuedoc htiw gnimmargorp

Using + (String concatenation) operator

We can utilize the string concatenation operator + to reverse a string in Java by reading characters from the other end and connecting them at the start of a new string. Take note that for an increment of the performance of repeated string concatenation, a Java compiler may use the “StringBuffer” class or look-alike formulae to reduce the total number of intermediate string objects generated by evaluation of expression:

class Main
{
	// Reversing a string in Java using the string concatenation operator
	public static String reverseString(String new_str)
	{
		// return if the string is either empty or null
		if (new_str == null || new_str.equals("")) {
			return new_str;
		}

		// variable storing the reversed string
		String rev_str = "";

		// use string concatenation operator to build a reversed string by
		// read the characters from the end of the original string
		for (int i = new_str.length() - 1; i >=0 ; i--) {
			rev_str += new_str.charAt(i);
		}

		return rev_str;
	}

	public static void main(String[] args)
	{
		String str = "coding made better with codeunderscored";

		str = reverse(str);		// string is immutable

		System.out.println("Reversed string is: " + str);
	}
}

The reversed string is: derocsrednuedoc htiw retteb edam gnidoc

Using Unicode Right-to-left override (RLO) character

In this event, we can utilize Unicode Right-to-left override approach to convert a string into its reverse. To present this, take a look at the sample below:

class usingUnicode
{
	// reversing a string in Java by Unicode
	// Right-to-left Override (RLO) character
	public static String reverseString(String new_str) {
		return "\u202E" + new_str;
	}

	public static void main(String[] args)
	{
		String str_val = "codeunderscored";

		// string is immutable
		str_val = reverse(str_val);

		System.out.println("The reversed string is: " + str);
	}
}

The reverse of the given string is: codeunderscored‬

Using a Byte Array

In this section, the idea is pretty straightforward. Just convert the given strings into bytes, and then in-place re-arranges the byte array as shown in this approach. Finally, we will convert the byte array back into a string. Take a look at the sample below:

import java.util.Arrays;

class usingByteArray
{
	// reversing a string in Java using a byte array
	public static String reverseString(String new_str)
	{
		// return if the specified string is either empty or null
		if (new_str == null || new_str.equals("")) {
			return new_str;
		}

		// converting strings into bytes
		byte[] n_bytes = str.getBytes();

		// starting from the two endpoints `l` and `h` of the given string
		// and increment `l` and decrement `h` at each iteration of the loop
		// until two endpoints intersect (l >= h)
		for (int l = 0, h = new_str.length() - 1; l < h; l++, h--)
		{
			// swap values at `l` and `h`
			byte temp_val = n_bytes[l];
			n_bytes[l] = n_bytes[h];
			n_bytes[h] = temp;
		}

		// convert byte array back into a string
		return new String(bytes);
	}

	public static void main(String[] args)
	{
		String str = "reverse codeunderscored";

		// String is immutable
		str = reverse(str);

		System.out.println("Reversed string is: " + str);
	}
}

The reversed string is: derocsrednuedoc esrever

Using Substring() method

We can also utilize String.substring(int, int) approach to attain a reverse on a string in Java. The subsequent code uses the String.charAt(int) method to segregate the first or last character of the and recur for the remaining string using substring()

Method 1:

class reverseUsingRecursion
{
	//  reversing a string in Java through recursion
	private static String reverseString(String new_str)
	{
		// base case: returns if given string is empty or null
		if (new_str == null || new_str.equals("")) {
			return new_str;
		}

		// last character + recur for the remaining string
		return new_str.charAt(new_str.length() - 1) +
				reverseString(new_str.substring(0, new_str.length() - 1));
	}

	public static void main(String[] args)
	{
		String str = "codeunderscored solves";

		// string is immutable
		str = reverse(str);

		System.out.println("Reversed string is: " + str);
	}
}

The reversed string is: sevlos derocsrednuedoc


Method 2:

class reverseUsingRecursion
{
	// reversing a string in Java using recursion
	public static String reverseString(String new_str)
	{
		// base case:  check if the string is null or empty
		if (new_str == null || new_str.equals("")) {
			return new_str;
		}

		// isolate the first character and recur for the remaining string
		return reverseString(new_str.substring(1)) + new_str.charAt(0);
	}

	public static void main(String[] args)
	{
		String str = "Reverse codeunderscored";

		// string is immutable
		new_str = reverseString(new_str);

		System.out.println("Reversed string is: " + new_str);
	}
}

The reversed string is: derocsrednuedoc esreveR

That is all there is on reversing the letters in a given String.

Conclusion

Nothing feels great as having the flexibility to do anything with your code, and that is exactly what we have given you in this article. We have looked at the different approaches to reversing a String in Java. We explored several examples with a bit of explanation to get you started. We hope the methods covered here have answered some rhetorical questions on string reversal in Java.

Similar Posts

Leave a Reply

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