How to Reverse the String in Java

String manipulation is a fundamental aspect of programming, and reversing a string is a common task that arises in various coding scenarios. In Java, there are multiple approaches to reversing a string, each with its own advantages and use cases. Whether you’re a Java beginner or an experienced developer, mastering these techniques can be a valuable addition to your programming toolbox.

In this blog, we will explore nine different methods to reverse a string in Java. We’ll provide code examples and explanations for each approach, highlighting their strengths and when to use them. 

Methods of How to Reserve the String in Java 

  1. Using recursion
  2. Converting to a byte array 
  3. Using XOR operation
  4. Using StringBuffer
  5. Using stack
  6. Using a list
  7. Creating a new string
  8. Swapping characters
  9. Using StringBuilder

Using recursion

Java code demonstrates a recursive approach to reverse a string.

// How to Reverse the String in Java
import java.util.*;
public class ReverseStrEx{
   static void reverse(String string)
   {
       if ((string==null)||(string.length() <= 1))
           System.out.println(string);
       else{
           System.out.print(string.charAt(string.length()-1));
           reverse(string.substring(0,string.length()-1));
       }
   }
   public static void main(String[] args) {
       String string  =  "Welcome";
       System.out.println("Original string: "+string);
       System.out.print("Reversed string: ");
       // recursive function call
       reverse(string);
   }
}

Explanation of the code:

1. The `reverse()` method takes a string as input and is responsible for reversing it.

2. In the base case, it checks if the string is either null or has a length of 1 or less. If true, it means there’s nothing to reverse, so it directly prints the string.

3. In the recursive case, it prints the last character of the string using `string.charAt(string.length()-1)` and then recursively calls itself with a substring that excludes the last character (`string.substring(0, string.length()-1)`).

4. This process continues until the base case is met for each recursive call, effectively reversing the string character by character.

5. In the `main()` method, a sample string “Welcome” is provided for reversal. The original string is printed, and then the `reverse()` function is called to reverse and print the string.

Output:

Original string: Welcome
Reversed string: emocleW

Converting to a byte array 

Java code demonstrates how to reverse a string using a byte array.

// How to Reverse the String in Java
import java.util.*;
public class ReverseStrEx{
   public static void main(String[] args) {
       String string  =  "Newtum";
       System.out.println("Original string: "+string);
       byte[] byteArray = string.getBytes();
       byte[] result = new byte[byteArray.length];
       // Store result in reverse order into the
       for (int i = 0; i < byteArray.length; i++)
           result[i] = byteArray[byteArray.length - i - 1];
       System.out.println("Reversed string: "+new String(result));
   }
}

Explanation of the code:

1. We begin by defining a string variable named `string`, which contains the original string we want to reverse.

2. The `getBytes()` method is used to convert the original string into a byte array called `byteArray`. Each character in the string is represented as a byte in the array.

3. We create another byte array called `result` with the same length as `byteArray`. This array will store the characters of the original string in reverse order.

4. In a loop that runs from 0 to the length of `byteArray`, we copy the bytes from `byteArray` into `result`, but in reverse order. We do this by accessing `byteArray` elements using the expression `byteArray[byteArray.length – i – 1]`. This effectively reverses the order of characters.

5. Finally, we create a new string by passing the `result` byte array to the `String` constructor. This new string contains the reversed version of the original string.

6. We print both the original and reversed strings to the console.

Output:

Original string: Newtum
Reversed string: mutweN

Using XOR operation

Below Java code below demonstrates how to reverse a string using a bitwise XOR operation.

// How to Reverse the String in Java
import java.util.*;
public class ReverseStrEx{
   public static void main(String[] args) {
       String string  =  "hello";
       System.out.println("Original string: "+string);
       // Converting String to Character Array
       char[] str = string.toCharArray();
       int low = 0;
       int high = str.length - 1;
       while (low < high) {
           str[low] = (char) (str[low] ^ str[high]);
           str[high] = (char) (str[low] ^ str[high]);
           str[low] = (char) (str[low] ^ str[high]);
           low++;
           high--;
       }
       System.out.print("Reversed string: ");
       //display reversed string
       for (int i = 0; i < str.length; i++) {
           System.out.print(str[i]);
       }
   }
}

Explanation of the code:

1. We start by defining the original string, which in this case is “hello,” and print it to the console.

2. To reverse the string, we convert it into a character array to allow for in-place modifications.

3. We initialize two pointers, `low` and `high`, at the beginning and end of the character array, respectively.

4. Inside the `while` loop, we perform the XOR swap operation between the characters at `low` and `high` positions. This operation effectively swaps the characters without the need for a temporary variable.

5. We continue swapping characters by moving the `low` pointer towards the center and the `high` pointer towards the center in each iteration of the loop.

6. The loop continues until the `low` pointer is less than the `high` pointer, ensuring that we reverse the entire string.

7. Finally, we print the reversed string by iterating through the character array and displaying each character.

Output:

Original string: hello
Reversed string: olleh

Using StringBuffer

The Java program below shows how to reverse a string using the `StringBuffer` class, a straightforward and efficient approach for string reversal.

// How to Reverse the String in Java
import java.util.*;
public class ReverseStrEx{
   public static void main(String[] args) {
       String str  =  "welcome";
       // Converting from String Object to StringBuffer
       StringBuffer reversedStringBuffer = new StringBuffer(str);
       reversedStringBuffer.reverse(); // reversing string
       System.out.println("Original String: "+str);
       System.out.println("Reversed String: "+reversedStringBuffer.toString());
   }
}

Explanation of the code:

1. We begin by initializing a string `str` with the value “welcome,” which we want to reverse.

2. Next, we create a `StringBuffer` object named `reversedStringBuffer` and initialize it with the original string `str`. `StringBuffer` is used here because it allows for efficient string manipulation.

3. We invoke the `reverse()` method on `reversedStringBuffer`. This method reverses the contents of the `StringBuffer` object in-place, effectively reversing the original string.

4. Finally, we print both the original and reversed strings using `System.out.println()`, displaying the results.

Output:

Original String: welcome
Reversed String: emoclew

Using stack

This Java code displays how to reverse a string using a stack data structure. Here’s an explanation of each part of the code:

// How to Reverse the String in Java
import java.util.Stack;
public class ReverseStrEx{
   public static void main(String[] args) {
       String string  =  "newtum";
       System.out.println("Original string: "+string);
       int n = string.length(); // length of String
       Stack<Character> stack = new Stack<>(); // Creating a stack object
       for(int i=0;i<n;i++){
           stack.push(string.charAt(i));
       }
       String reversedString = "";
       // popped characters will be in reversed order
       while(!stack.isEmpty()){
           reversedString+=stack.pop();
       }
       System.out.println("Reversed string: "+reversedString); // Printing the reversed string
   }
}

Explanation of the code:
1. We start by defining the original string, which is “newtum,” and print it to show the initial content.

2. We calculate the length of the string using `string.length()`, which is essential for looping through the characters.

3. We create a `Stack` object called `stack` to store characters temporarily. A stack follows the Last-In-First-Out (LIFO) principle, making it ideal for reversing the order of characters.

4. Using a `for` loop, we iterate through each character in the original string. Within the loop, `stack.push(string.charAt(i))` pushes each character onto the stack.

5. We initialize an empty string called `reversedString` to hold the reversed characters.

6. In the while loop `while (!stack.isEmpty())`, we pop characters from the stack using `stack.pop()` and append them to the `reversedString`. This step effectively reverses the order of characters, as characters are popped from the stack in reverse order.

7. Finally, we print the “Reversed string” to display the result, which now contains the original string reversed: “mutwen.”

Output:

Original string: newtum
Reversed string: mutwen

Using a list

This Java code snippet showcases how to reverse a string using an ArrayList to store and manipulate characters:

// How to Reverse the String in Java
import java.util.*;
public class ReverseStrEx{
   public static void main(String[] args) {
       String string = "funny";
       System.out.println("Original string: "+string);
       char str[] = string.toCharArray();
       int n = str.length; 
       ArrayList<Character> list = new ArrayList<>();
       for(int i=0;i<n;i++){ // Iterating through characterArray and adding character into list
           list.add(str[i]);
       }
       Collections.reverse(list); // Reversing list
       int size = list.size(); // size of ArrayList
       System.out.print("Reversed string: ");
       for(int i=0;i<size;i++){
           // Printing characters from ArrayList in reversed manner
           System.out.print(list.get(i));
       }
   }
}

Explanation of the code:

1. Input String We begin with the original string, “funny,” which we intend to reverse.

2. Converting to Character Array: We convert the input string into a character array (`char[] str`) to facilitate individual character manipulation.

3. ArrayList: We create an ArrayList of characters (`ArrayList<Character> list`) to dynamically store and manipulate the characters during the reversal process.

4. Character Addition: Using a for loop, we iterate through the character array and add each character to the ArrayList. This effectively breaks down the string into its individual characters.

5. Reversing the ArrayList: We use the `Collections.reverse(list)` method to reverse the order of characters stored in the ArrayList.

6. Printing Reversed String: Finally, we retrieve and print the characters from the ArrayList in reverse order, effectively displaying the reversed string.

Also, learn about  Multiply Two Matrices in Java, Now!

Output:

Original string: funny
Reversed string: ynnuf

Creating a new string

This Java code demonstrates a simple approach to reverse a string.

// How to Reverse the String in Java
public class ReverseStrEx{
   public static void main(String[] args) {
       String string  =  "java";
       System.out.println("Original string: "+string);
       int n = string.length(); // length of String
       String reversedString ="";
       char character;
       for(int i=0;i<n;i++){
           character= string.charAt(i);
           //concatenates each character in front of the new string
           reversedString = character+reversedString;
       }
       System.out.println("Reversed string: "+reversedString); //  Printing the reversed String
   }
}

Explanation of the code:

1. It initializes a string variable, “string,” with the value “java.” The code then calculates the length of the string using the “length()” method and stores it in the variable “n.”

2. A new empty string, “reversedString,” is created to store the reversed result. The code uses a “for” loop to iterate through each character of the original string. Inside the loop, it extracts each character using the “charAt()” method and then concatenates it to the beginning of the “reversedString.” 

3. This process effectively reverses the string character by character. After the loop, the code prints the original and reversed strings. In this example, the original string “java” becomes “avaj” when reversed.

This straightforward method is easy to understand and implement for string reversal in Java, making it suitable for various scenarios.

Output:

Original string: java
Reversed string: avaj

Start practicing with our expertly curated AngularJS interview questions and shine in your interviews!

Swapping characters

The Java code presented here is a straightforward way to reverse a string using the `StringBuilder` class.

// How to Reverse the String in Java
public class ReverseStrEx{
   public static void main(String[] args) {
       String string  =  "Example";
       System.out.println("Original string: "+string);
       // Converting String to Character Array
       char str[] = string.toCharArray();
       int n = str.length; // length of character array
       int start=0,end = n-1;
       while(start<=end){
           // Swapping the characters
           char temp = str[start];
           str[start] = str[end];
           str[end] = temp;
           start++;
           end--;
       }
       //  Converting characterArray to String
       String reversedString = String.valueOf(str);
       System.out.println("Reversed string: "+reversedString); 
   }
}

Explanation of the code:

1. We begin by initializing a string `str` with the value “Welcome” and display it as the original string.

2. Next, we declare a `StringBuilder` named `reverseString` and initialize it with the original string `str`. This step is crucial because `StringBuilder` offers a convenient `reverse()` method to reverse its content efficiently.

3. We call the `reverse()` method on the `reverseString` object, which reverses the characters within the `StringBuilder`.

4. To obtain the reversed string in the standard string format, we convert the `StringBuilder` back to a string using the `toString()` method and store it in the `result` variable.

5. Finally, we print the reversed string, and the output shows the original string “Welcome” reversed as “emocleW.”

Output:

Original string: Example
Reversed string: elpmaxE

Using StringBuilder

The below Java Program uses an approach that utilizes Java’s built-in `StringBuilder` class for efficient string manipulation, providing a quick and straightforward solution for reversing strings in Java.

// How to Reverse the String in Java
public class ReverseStrEx{
   public static void main(String[] args) {
       String str  =  "Welcome";
       System.out.println("Original string: "+str);
       // Declaring a StringBuilder and converting string to StringBuilder
       StringBuilder reverseString = new StringBuilder(str);
       reverseString.reverse();  // Reversing the StringBuilder
       // Converting StringBuilder to String
       String result = reverseString.toString();
       System.out.println("Reversed string: "+result); 
   }
}

Dive into the world of data structures in Python and take control of your data.

Explanation of the code:

1. We begin by initializing a string `str` with the value “Welcome” and display it as the original string.

2. Next, we declare a `StringBuilder` named `reverseString` and initialize it with the original string `str`. This step is crucial because `StringBuilder` offers a convenient `reverse()` method to reverse its content efficiently.

3. We call the `reverse()` method on the `reverseString` object, which reverses the characters within the `StringBuilder`.

4. To obtain the reversed string in the standard string format, we convert the `StringBuilder` back to a string using the `toString()` method and store it in the `result` variable.

5. Finally, we print the reversed string, and the output shows the original string “Welcome” reversed as “emocleW.”

Output:

Original string: Welcome
Reversed string: emocleW

In this exploration of string reversal methods in Java, we’ve journeyed through diverse techniques, from recursion to StringBuilder. Each method has its unique strengths, providing Java developers with a versatile toolkit for string manipulation. Embrace these techniques to efficiently reverse strings and meet various programming needs.

Our blog post on ‘How to Reverse the String in Java’’ able to provide valuable information. You can also visit our Newtum website for more information on various courses and blogs about  PHP, C Programming for kids, Java, and more. Happy coding!

About The Author

Leave a Reply