How To Reverse A String In Java: Explained

Reversing a string is one of the most common beginner exercises in Java, and it's also a frequent interview question because there are several different approaches, each demonstrating a different Java concept.

Method 1: Using StringBuilder

The simplest and most efficient approach uses the built-in reverse() method of the StringBuilder class.

String str = "Uncodemy";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // ymedocnU

Method 2: Using a Character Array

Convert the string into a character array, then swap characters from both ends toward the middle.

char[] chars = str.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
    char temp = chars[left];
    chars[left] = chars[right];
    chars[right] = temp;
    left++;
    right--;
}
System.out.println(new String(chars));

Method 3: Using a for Loop

Build a new string by appending characters starting from the end of the original string.

String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
    result += str.charAt(i);
}
System.out.println(result);

Method 4: Using Recursion

A recursive approach reverses the rest of the string first, then appends the first character at the end.

static String reverseRecursive(String s) {
    if (s.isEmpty()) {
        return s;
    }
    return reverseRecursive(s.substring(1)) + s.charAt(0);
}

Which Method Should You Use?

  • StringBuilder.reverse() — best for real-world code, fastest and cleanest
  • Character array swap — good for understanding how reversal works internally
  • for loop with concatenation — simple but inefficient for long strings
  • Recursion — useful for learning recursive thinking, but less efficient than iterative methods
In production code, always prefer StringBuilder.reverse() — manual loop-based string concatenation creates many unnecessary intermediate String objects.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course