Reverse Of The String In Java

7 min read

Reverse of the String in Java: A Complete Guide

Reversing a string is one of the most common programming tasks that beginners encounter when learning Java. On top of that, whether you are preparing for an interview, solving algorithmic problems, or simply manipulating text in an application, knowing how to reverse of the string in java efficiently is essential. This article walks you through multiple approaches, explains the underlying mechanics, and provides practical examples you can run immediately That's the part that actually makes a difference. That alone is useful..


Why String Reversal Matters

Strings are immutable in Java, meaning once a String object is created its contents cannot be changed. Reversing a string therefore requires creating a new sequence that contains the original characters in opposite order. Mastering this operation helps you understand:

  • Immutability and how to work around it using mutable helpers like StringBuilder or StringBuffer.
  • Loop constructs and recursion fundamentals.
  • Performance trade‑offs between different techniques.

Approaches to Reverse a String in Java

Below are the most widely used methods, each with its own advantages. Choose the one that best fits your scenario.

1. Using StringBuilder (Recommended)

StringBuilder provides a mutable sequence of characters and a built‑in reverse() method. This is the fastest and most readable way for most applications.

public class StringReverseDemo {
    public static String reverseWithStringBuilder(String input) {
        if (input == null) {
            return null;
        }
        return new StringBuilder(input).reverse().toString();
    }

    public static void main(String[] args) {
        String original = "Hello, World!Because of that, ";
        String reversed = reverseWithStringBuilder(original);
        System. On top of that, out. println("Original: " + original);
        System.out.

**Explanation**  

* `new StringBuilder(input)` creates a mutable copy of the string.  
* `.reverse()` internally swaps characters from the ends toward the center.  
* `.toString()` converts the mutable sequence back to an immutable `String`.  

**Complexity** – Time **O(n)**, Space **O(n)** (for the new `StringBuilder` object).

### 2. Using a Character Array and Two‑Pointer Technique  

If you prefer to avoid `StringBuilder`, you can manually swap characters in a `char[]`. This demonstrates the classic two‑pointer algorithm.

```java
public static String reverseWithCharArray(String input) {
    if (input == null) {
        return null;
    }
    char[] chars = input.toCharArray();
    int left = 0;
    int right = chars.length - 1;
    while (left < right) {
        // swap chars[left] and chars[right]
        char temp = chars[left];
        chars[left] = chars[right];
        chars[right] = temp;
        left++;
        right--;
    }
    return new String(chars);
}

Explanation

  • Convert the string to a char[] because arrays are mutable.
  • Use two indices (left and right) that move toward each other, swapping elements until they meet.
  • Finally, create a new String from the modified array.

Complexity – Same as StringBuilder: O(n) time, O(n) auxiliary space for the char array.

3. Using Recursion

Recursion offers an elegant, though less efficient, solution. It is useful for teaching concepts like call stack and base case Most people skip this — try not to..

public static String reverseRecursively(String input) {
    if (input == null || input.length() <= 1) {
        return input; // base case
    }
    // recursive step: last character + reverse of the substring without last char
    return input.charAt(input.length() - 1) +
           reverseRecursively(input.substring(0, input.length() - 1));
}

Explanation

  • Base case: strings of length 0 or 1 are already reversed.
  • Recursive case: take the last character, then recursively reverse the prefix.

Complexity – Time O(n²) because each substring call copies characters; space O(n) due to recursion depth.

4. Using Java 8 Streams (Functional Style)

Streams provide a declarative way to reverse a string, though they involve boxing overhead Easy to understand, harder to ignore..

import java.util.stream.Collectors;

public static String reverseWithStreams(String input) {
    if (input == null) {
        return null;
    }
    return input.Collections.Which means util. collect(Collectors.Think about it: mapToObj(c -> (char) c)    // Stream
                . collectingAndThen(
                        Collectors.Day to day, toList(),
                        list -> {
                            java. reverse(list);
                            return list.map(String::valueOf)
                                       .stream()
                                       .chars()                     // IntStream of char codes
                .collect(Collectors.

**Explanation**  

* `chars()` yields an `IntStream` of Unicode code points.  
* Convert to `Stream`, collect to a `List`, reverse the list, then join back into a string.  

**Complexity** – Time **O(n)**, Space **O(n)** (for the list and intermediate objects).  

---

## Performance Comparison  

| Method                     | Time Complexity | Extra Space | Remarks |
|----------------------------|-----------------|------------|---------|
| `StringBuilder.reverse()`  | O(n)            | O(n)       | Fastest, simplest, recommended |
| Char array + two‑pointer   | O(n)            | O(n)       | Good for low‑level control |
| Recursion                  | O(n²) (due to substring) | O(n) (call stack) | Educational, not production‑ready |
| Streams                    | O(n)            | O(n)       | Functional style, higher overhead |

For most real‑world applications, **`StringBuilder`** is the go‑to solution.

---

## Handling Edge Cases  

When implementing string reversal, always consider the following scenarios:

* **Null input** – Return `null` or throw an `IllegalArgumentException` based on your API contract.  
* **Empty string** – Should return an empty string (`""`).  
* **Unicode surrogate pairs** – Basic `char` reversal can break combined characters (e.g., emojis). For full Unicode safety, convert to `int[]` code points before reversing:

```java
public static String reverseUnicodeSafe(String input) {
    if (input == null) {
        return null;
    }
    int[] codePoints = input.codePoints().toArray();
    for (int i = 0, j = codePoints.length - 1; i < j; i++, j--) {
        int tmp = codePoints[i];
        codePoints[i] = codePoints[j];
        codePoints[j] = tmp;
    }
    return new String(codePoints, 0, codePoints.length);
}

This version treats each Unicode code point as an atomic unit, preserving characters that consist of multiple char values Small thing, real impact..


Frequently Asked Questions (FAQ)

Q1: Can I reverse a string in‑place without extra memory?
A: Because String objects are immutable in Java, true in‑place reversal is impossible without converting to a mutable structure (like char[] or StringBuilder). The extra memory is unavoidable for a pure‑Java solution.

Q2: Is StringBuilder thread‑safe?
A: No. StringBuilder is unsynchronized and therefore faster. If you

If you need thread safety, use StringBuffer (its methods are synchronized) or, better, avoid shared mutable state altogether by creating a new StringBuilder inside each method call — local variables are inherently thread-safe. In practice, the overhead of synchronization rarely justifies itself unless multiple threads are concurrently modifying the same buffer, which is an uncommon scenario for string reversal Easy to understand, harder to ignore..

Q3: What about performance for very large strings?
A: For very large strings, the O(n) time and space of StringBuilder remains optimal. That said, memory allocation can become a bottleneck. In such cases, consider processing the string in chunks or using a CharBuffer with a custom reverse view. For most applications, the default StringBuilder approach is sufficient.

Q4: Are there any built-in methods in Java 11 or later that simplify reversal?
A: Java does not provide a direct String.reverse() method. The closest built-in is new StringBuilder(input).reverse().toString(). For Unicode-safe reversal, you must still use the code-point approach shown earlier. No standard library method handles surrogate pairs automatically for reversal.

Q5: How does string reversal differ in other JVM languages like Kotlin?
A: Kotlin offers a built-in reversed() extension function that works on String and handles Unicode correctly (it reverses by code points). Under the hood, it uses a StringBuilder-like mechanism. If you're writing mixed Java/Kotlin code, you can rely on Kotlin's standard library for a concise, safe reversal.


Best Practices

  1. Prefer StringBuilder for production code – it’s simple, fast, and readable.
  2. Always handle null and empty inputs consistently with your API contract.
  3. Use the code-point version if your application deals with international text or user-generated content that may include emojis or rare scripts.
  4. Avoid recursion for string reversal – the quadratic time and stack risk are not worth the educational value in production.
  5. Write unit tests covering edge cases: null, empty, single character, palindrome, surrogate pairs, and combining characters.

Conclusion

Reversing a string in Java is a fundamental task that illustrates the language’s balance between simplicity and control. Day to day, the StringBuilder. reverse() method remains the most straightforward and efficient choice for the vast majority of use cases, offering linear time and space complexity with minimal code. For developers needing finer control or Unicode correctness, the char-array and code-point approaches provide reliable alternatives.

Understanding the trade-offs between these methods — from the elegance of streams to the low-level manual swapping — equips you to select the right tool for your specific requirements. Whether you’re processing user input, preparing data for display, or building algorithms, the techniques outlined here ensure your string reversal is both correct and performant.

By applying the best practices and edge-case handling discussed, you can confidently implement string reversal in any Java application, knowing that your code is clean, efficient, and ready for the complexities of real-world text The details matter here..

What's Just Landed

New Arrivals

Explore the Theme

Related Reading

Thank you for reading about Reverse Of The String In Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home