Reverse String in Java: Solution, Explanation & Practice

Reverse a string

Problem summary

Write a program that reverses any given string.

Starter code

public class Main {
    public static void main(String[] args) {
        String text = "Hello"; // Test case 1
        
        // Reverse the string
        // Print: Reversed: <result>
    }
}

Expected output and test cases

  • Reverse Hello
    Reversed: olleH
  • Reverse Java
    Reversed: avaJ
  • Single character
    Reversed: a

Hints

  1. Use StringBuilder's reverse() method
  2. Or iterate from end to start
  3. Build new string character by character

Validated solution

Reveal Java solution
public class Main {
    static String reverse(String text) {
        StringBuilder result = new StringBuilder(text.length());
        for (int index = text.length() - 1; index >= 0; index--) result.append(text.charAt(index));
        return result.toString();
    }
    public static void main(String[] args) {
        System.out.println("Reversed: " + reverse("Hello"));
    }
}

How to approach the problem

Read characters from the final index down to zero and append them to one StringBuilder. The builder avoids creating a new immutable String after every character append.

Approach

  1. Allocate a builder with the known final length.
  2. Visit indices from length - 1 down to zero.
  3. Convert the builder once at the boundary.

Time and space complexity

Time: O(n). Space: O(n).

Edge cases to test

  • An empty string stays empty.
  • charAt works on UTF-16 code units; code-point-aware reversal is a different requirement.

Common mistakes

  • Starting at text.length(), which is outside the valid index range.
  • Repeatedly concatenating with + in a loop.

Follow-up challenge

Reverse Unicode code points without splitting an emoji surrogate pair.

Related Strings exercises

Practice all Strings exercises · Run this idea in the Java compiler