DEV Community

Cover image for How to Reverse a String in Java: A Comprehensive Guide
JavaFullStackDev.in
JavaFullStackDev.in

Posted on

How to Reverse a String in Java: A Comprehensive Guide

Reversing a string is a common programming task that can be approached in several ways. In this blog, we'll explore various methods to reverse a string in Java, providing detailed explanations and sample code for each approach.

1. Using StringBuilder

The StringBuilder class in Java provides a convenient way to reverse a string. This class has a built-in method called reverse() which we can use.

Code Example:

public class ReverseStringExample {
    public static void main(String[] args) {
        String input = "Hello, World!";
        StringBuilder sb = new StringBuilder(input);
        String reversed = sb.reverse().toString();
        System.out.println("Reversed String: " + reversed);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. We create a StringBuilder object and initialize it with the input string.
  2. We call the reverse() method on the StringBuilder object.
  3. We convert the StringBuilder object back to a string using the toString() method.
  4. Finally, we print the reversed string.

2. Using a Character Array

Another way to reverse a string is by converting it into a character array, reversing the array, and then constructing a new string from the reversed array.

Code Example:

public class ReverseStringExample {
    public static void main(String[] args) {
        String input = "Hello, World!";
        char[] charArray = input.toCharArray();
        int left = 0;
        int right = charArray.length - 1;

        while (left < right) {
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;
            left++;
            right--;
        }

        String reversed = new String(charArray);
        System.out.println("Reversed String: " + reversed);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Convert the input string into a character array using toCharArray().
  2. Initialize two pointers, left at the beginning and right at the end of the array.
  3. Swap the characters at these two pointers.
  4. Move the pointers towards the center.
  5. Repeat the process until the pointers meet in the middle.
  6. Convert the reversed character array back to a string and print it.

3. Using Recursion

Recursion can also be used to reverse a string by breaking it down into smaller substrings.

Code Example:

public class ReverseStringExample {
    public static void main(String[] args) {
        String input = "Hello, World!";
        String reversed = reverseString(input);
        System.out.println("Reversed String: " + reversed);
    }

    public static String reverseString(String str) {
        if (str.isEmpty()) {
            return str;
        }
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Define a recursive method reverseString() that takes a string as input.
  2. If the string is empty, return the string (base case).
  3. Otherwise, return the reverse of the substring starting from the second character (str.substring(1)) concatenated with the first character (str.charAt(0)).
  4. The recursion continues until the base case is reached.
  5. Print the reversed string.

4. Using Collections API

Java's Collections class can also be used to reverse a string by working with a list of characters.

Code Example:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ReverseStringExample {
    public static void main(String[] args) {
        String input = "Hello, World!";
        List<Character> charList = new ArrayList<>();

        for (char c : input.toCharArray()) {
            charList.add(c);
        }

        Collections.reverse(charList);
        StringBuilder sb = new StringBuilder(charList.size());
        for (char c : charList) {
            sb.append(c);
        }

        String reversed = sb.toString();
        System.out.println("Reversed String: " + reversed);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Convert the input string into a list of characters.
  2. Use the Collections.reverse() method to reverse the list.
  3. Construct a new string from the reversed list using StringBuilder.
  4. Print the reversed string.

Conclusion

Reversing a string in Java can be accomplished in various ways, each with its own advantages and nuances. Whether you use the StringBuilder, a character array, recursion, or the Collections API, understanding these methods will enhance your ability to manipulate strings effectively in Java.

Feel free to choose the method that best suits your needs and the specific context of your application. Happy coding!

Top comments (0)