How to Reverse a String in Java

Naveen AnamaneniUpdated · 4 min read

"Reverse a string" is often the first coding question in a fresher interview. The interviewer usually wants to see two things: that you know the built-in way, and that you can do it by hand with a loop, which shows you understand indexes. This lesson covers both, plus recursion, and explains one trap that even experienced developers miss.

The Built-In Way

BuiltIn.java▶ Try it
public class BuiltIn {
    public static void main(String[] args) {
        String reversed = new StringBuilder("hello").reverse().toString();
        System.out.println(reversed);
    }
}
Output
olleh

Strings can't change, so you copy the text into a StringBuilder, reverse it there, and turn it back into a String. This is the version to use in real code.

By Hand: Swapping from Both Ends

Swap the outer pair, move inward, stop when the pointers meet
TwoPointer.java▶ Try it
public class TwoPointer {
    static String reverse(String s) {
        char[] c = s.toCharArray();
        for (int i = 0, j = c.length - 1; i < j; i++, j--) {
            char temp = c[i];
            c[i] = c[j];
            c[j] = temp;
        }
        return new String(c);
    }
 
    public static void main(String[] args) {
        System.out.println(reverse("Navika"));
        System.out.println(reverse("racecar"));
        System.out.println("[" + reverse("") + "]");
    }
}
Output
akivaN
racecar
[]

How it works

  1. toCharArray() gives an array you can change.
  2. i starts at the first position and j at the last. Each pass swaps those two characters, then moves both pointers inward.
  3. The loop stops when they meet (i < j is false), so each character moves exactly once: about n/2 swaps for n characters.
  4. A palindrome like "racecar" reads the same both ways, and an empty string stays empty.

Two More Ways

OtherWays.java▶ Try it
public class OtherWays {
    static String backward(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = s.length() - 1; i >= 0; i--) {
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }
 
    static String recursive(String s) {
        if (s.isEmpty()) {
            return s;
        }
        return recursive(s.substring(1)) + s.charAt(0);
    }
 
    public static void main(String[] args) {
        System.out.println(backward("Srihitha"));
        System.out.println(recursive("Advitha"));
    }
}
Output
ahtihirS
ahtivdA
WayExtra memoryNotes
StringBuilder.reverse()One builderShortest; handles emoji correctly
Two-pointer swapOne char[]The classic interview answer
Backward loopOne builderEasy to read
RecursionA new string per levelElegant, but slow and can overflow the stack for long text

The Emoji Trap

Emoji take two chars in Java (see "Character Encoding and Charsets in Java"). A hand-written swap reverses those two halves too, which breaks the emoji into two invalid pieces. StringBuilder.reverse() knows about these pairs and keeps them together:

Method"ab😀" reversed
new StringBuilder("ab😀").reverse()😀ba (correct)
Two-pointer swap on toCharArray()Two broken characters, then ba

Common Mistakes

Building the result with += in the loop. It's slow for long strings; use a StringBuilder or a char[].

Looping with i <= j and swapping the middle character with itself. Harmless, but i < j is cleaner.

Recursion on very long text. Each character adds a stack frame and a new string.

Interview Corner

How do you reverse a string in Java?

The simplest way is new StringBuilder(s).reverse().toString(), which also keeps surrogate pairs such as emoji intact. Manually, convert the string to a char[] and swap characters from both ends with two indexes moving toward the middle, then build a new String from the array. That takes linear time and n/2 swaps.

Practice

  1. Easy: Reverse each word in "Java is fun" separately, giving "avaJ si nuf".
  2. Harder: Write static boolean isPalindrome(String s) with the two-pointer idea, without building a reversed copy, ignoring case.

Quick check: Reversing strings

4 questions
1What does new StringBuilder("abc").reverse().toString() return?
2In the two-pointer method, when does the loop stop?
3How many swaps does the two-pointer method need for 6 characters?
4Which method keeps emoji intact?

Key Takeaways

Was this tutorial helpful?

Lesson 207 of 482