How To Reverse A String In Java

5 min read

How to Reverse a String in Java: A Complete Guide for Every Level

Reversing a string is one of the most common programming exercises you’ll encounter when learning Java—or any language, for that matter. Which means it’s a simple task that hides a surprising amount of depth, touching on core concepts like immutability, character encoding, and recursion. In Java, reversing a string isn’t as straightforward as calling a single built-in method on the String class (because String objects are immutable), but Several elegant ways exist — each with its own place. Whether you’re preparing for a coding interview or just brushing up on your Java fundamentals, this guide will walk you through every practical approach, explain how each one works under the hood, and help you choose the right method for your specific situation.


Why Reversing a String in Java Requires Special Attention

Before diving into code, it’s essential to understand why reversing a string in Java isn’t as trivial as it might seem. That said, any operation that appears to modify a string—like concatenation or replacement—actually creates a brand-new String object in memory. In Java, String objects are immutable, meaning that once a String is created, it cannot be changed. This is a deliberate design choice for security, caching, and thread safety, but it means you can’t simply swap characters in place within the original string Practical, not theoretical..

Quick note before moving on.

Because of this immutability, reversing a string requires you to build a new string character by character, or to use a mutable helper class like StringBuilder or StringBuffer. Let’s explore the most common and effective methods, starting with the simplest.


Method 1: Using StringBuilder or StringBuffer (The Easiest Way)

The most straightforward and widely recommended approach in modern Java is to use the reverse() method provided by the StringBuilder class (or its thread-safe cousin, StringBuffer). This method is concise, readable, and does exactly what you need with minimal room for error.

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

How it works:
The StringBuilder is initialized with the original string. Its reverse() method swaps the characters in the underlying mutable character array in place, and then toString() converts the result back into a new immutable String That alone is useful..

When to use it:

  • When you want the cleanest, most maintainable code.
  • When you don’t need thread safety (which is almost always the case).
  • When performance is acceptable for most use cases (it’s O(n) time complexity, same as any other method).

What about StringBuffer?
StringBuffer is the older, synchronized version of StringBuilder. Because of that synchronization overhead, it’s slower in single-threaded contexts. Unless you’re working with multiple threads and need to reverse a string safely, prefer StringBuilder.


Method 2: Reversing with a Character Array (Manual Approach)

If you want to understand the underlying logic—or you’re in an environment where you can’t use StringBuilder (like a coding challenge that forbids it)—you can reverse the string manually using a char[] array. This method gives you full control and is a great way to demonstrate your understanding of array indexing.

Honestly, this part trips people up more than it should.

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 characters at left and right indices
        char temp = chars[left];
        chars[left] = chars[right];
        chars[right] = temp;
        left++;
        right--;
    }
    return new String(chars);
}

How it works:

  1. Convert the string into a char[] array.
  2. Use two pointers: one starting at the beginning (left) and one at the end (right).
  3. Swap the characters at these positions, then move the pointers toward each other until they meet in the middle.
  4. Create a new String from the modified array.

Why this is educational:
This approach teaches you the classic two-pointer technique, which is useful in many other algorithms (like checking palindromes or finding pairs in a sorted array). It’s also memory-efficient because it uses only one extra array of the same size.


Method 3: Recursive Reversal (Elegant but Inefficient)

Recursion is a favorite topic in interviews, and reversing a string recursively is a classic exercise. The idea is to break the problem into smaller subproblems: take the last character and append the reverse of the remaining substring That's the part that actually makes a difference. Worth knowing..

public static String reverseRecursively(String input) {
    if (input == null || input.length() <= 1) {
        return input;
    }
    return reverseRecursively(input.substring(1)) + input.charAt(0);
}

How it works:

  • Base case: If the string is empty or has only one character, it’s already reversed.
  • Recursive step: Take the substring starting from index 1 (i.e., everything except the first character), reverse it, and then append the first character at the end.

Here's one way to look at it: reverse("hello") becomes:
reverse("ello") + 'h'(reverse("llo") + 'e') + 'h' → ... and so on.

When to use it (and when not to):

  • Use it if you’re specifically asked to demonstrate recursion in an interview.
  • Avoid it in production code. This method creates many intermediate String objects due to substring() and string concatenation, leading to O(n²) time and space complexity in the worst case. It can also cause a StackOverflowError for very long strings because each recursive call consumes stack memory.

Method 4: Using Java 8 Streams (Functional Approach)

If you’re working with Java 8 or later, you can use the Stream API to reverse a string in a functional style. This method is less common but showcases your familiarity with modern Java features.

public static String reverseWithStreams(String input) {
    if (input == null) {
        return null;
    }
    return input.chars()
                .mapToObj(c -> String.valueOf((char) c))
                .reduce("", (reversed, character) -> character + reversed);
}

How it works:

  1. input.chars() returns an IntStream of the character codes.
  2. `map
Just Came Out

Out Now

Worth Exploring Next

Similar Reads

Thank you for reading about How To Reverse A 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