Java
Programming
String Manipulation
Coding Tutorial
Java String Reverse

Reverse a string in Java

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Reversing a string is simple in Java if all you need is a quick utility, but the "best" approach depends on what you care about: readability, interview clarity, or full Unicode correctness. For everyday code, StringBuilder.reverse() is usually the cleanest answer, while manual loops are still useful for understanding the mechanics.

The Practical Default: StringBuilder.reverse()

The shortest and most idiomatic solution in normal Java code is to use StringBuilder.

java
1public class ReverseDemo {
2    public static String reverse(String input) {
3        return new StringBuilder(input).reverse().toString();
4    }
5
6    public static void main(String[] args) {
7        System.out.println(reverse("hello"));
8    }
9}

This is concise, fast enough for most cases, and easy for other Java developers to recognize immediately.

It is usually the right answer unless you are solving the problem for educational purposes or need special handling for certain character cases.

Manual Reversal with a Loop

If you want to see the logic explicitly, create a character array and fill it from the back.

java
1public class ReverseWithLoop {
2    public static String reverse(String input) {
3        char[] result = new char[input.length()];
4
5        for (int i = 0; i < input.length(); i++) {
6            result[input.length() - 1 - i] = input.charAt(i);
7        }
8
9        return new String(result);
10    }
11
12    public static void main(String[] args) {
13        System.out.println(reverse("world"));
14    }
15}

This approach is still O(n) in time and O(n) in extra space, but it makes the indexing logic visible, which is why it shows up in interviews and algorithm practice.

Building the String Backward

Another common pattern is to append characters from the end of the string toward the beginning.

java
1public class ReverseByAppending {
2    public static String reverse(String input) {
3        StringBuilder sb = new StringBuilder();
4
5        for (int i = input.length() - 1; i >= 0; i--) {
6            sb.append(input.charAt(i));
7        }
8
9        return sb.toString();
10    }
11
12    public static void main(String[] args) {
13        System.out.println(reverse("java"));
14    }
15}

This is also clear and efficient enough. It is slightly more verbose than using StringBuilder.reverse(), but it is still a reasonable manual solution.

Why Plain String Concatenation Is a Bad Idea

Beginners often write something like this:

java
1public static String reverseBad(String input) {
2    String result = "";
3
4    for (int i = input.length() - 1; i >= 0; i--) {
5        result += input.charAt(i);
6    }
7
8    return result;
9}

This works, but it creates many intermediate strings because Java strings are immutable. For long inputs, that is wasteful and much slower than using StringBuilder.

So if you reverse manually, use a StringBuilder or a preallocated char[], not repeated string concatenation.

Streams Are Possible but Rarely the Best Choice

You can force the problem into a more functional style, but it is usually less readable than the straightforward options.

java
1import java.util.stream.IntStream;
2
3public class ReverseWithStreams {
4    public static String reverse(String input) {
5        StringBuilder sb = new StringBuilder();
6        IntStream.range(0, input.length())
7                 .map(i -> input.length() - 1 - i)
8                 .forEach(i -> sb.append(input.charAt(i)));
9        return sb.toString();
10    }
11}

This is fine as an exercise, but it is not the clearest production solution.

Unicode and Character Boundaries

One subtle issue is that Java char values are UTF-16 code units, not always full user-perceived characters. Some Unicode characters and emoji involve surrogate pairs or combining sequences.

That means naive reversal can produce visually surprising results for some text.

For ordinary ASCII or typical Latin-alphabet strings, this is not a practical problem. But if you are reversing arbitrary user-visible Unicode text, the question becomes more complex than simple character order.

So when someone asks "How do I reverse a string in Java?" the usual coding answer is straightforward. When the requirement becomes "reverse visible characters correctly for all Unicode cases," the problem is more nuanced.

Choosing the Right Method

A simple rule of thumb:

  • use StringBuilder.reverse() for normal application code
  • use a loop or char[] when teaching or demonstrating the algorithm
  • avoid repeated string concatenation in loops
  • think carefully about Unicode if the input is arbitrary user text

That covers most real scenarios.

Common Pitfalls

The most common mistake is using result += ... inside a loop, which is much less efficient than using StringBuilder.

Another issue is assuming the interview version and the production version must be the same. In real code, the built-in library method is usually the right choice.

Developers also forget to handle null if the surrounding code allows it. A reverse helper should either reject null clearly or define how it is handled.

Finally, if your application deals with rich Unicode text, do not assume reversing UTF-16 code units always matches human expectations about character order.

Summary

  • 'StringBuilder.reverse() is the usual practical answer in Java.'
  • Manual loops and char[] implementations are useful for learning and interviews.
  • Avoid building the reversed string with repeated += concatenation.
  • Streams can work, but they are usually less clear for this task.
  • Be aware that full Unicode-aware reversal is more complicated than reversing char positions.

Course illustration
Course illustration

All Rights Reserved.