Java Program to Reverse a String Without Using StringBuilder.reverse()

Introduction

Reversing a String without using StringBuilder.reverse() is a common Java coding interview question. The task is to reverse the order of characters in a String by implementing the reversal logic yourself.

For example, if the input is "Java", the expected output is "avaJ". You can achieve this by reading characters from the end of the String toward the beginning or by swapping characters in an array.

This problem helps you understand how Strings, arrays, loops, and indexes work in Java. It also demonstrates an important difference between immutable Strings and mutable character arrays.

In this tutorial, I will demonstrate three ways to reverse a String without calling StringBuilder.reverse(). I will start with a simple for loop, explain the two-pointer technique, and show how to handle supplementary Unicode characters correctly.

1. Understanding String Reversal in Java

String reversal means arranging the characters of a String in the opposite order.

Consider the following input:

Java

The expected output is:

avaJ

The original and reversed character positions are shown below.

Index Original Reversed
0Ja
1av
2va
3aJ

Java Strings are immutable. This means that you cannot modify an existing String directly.

To reverse a String, you must create a new sequence of characters in the required order.

2. Reverse a String Using a For Loop

One of the simplest ways to reverse a String is to use a for loop that starts at the last character and moves toward the first.

The program reads each character using charAt() and appends it to a new String using a StringBuilder.

Although this approach uses StringBuilder to construct the result efficiently, it does not use the reverse() method. The reversal logic is implemented manually.

Java Program Using a For Loop

public class ReverseStringUsingLoop {

    public static void main(String[] args) {

        String input = "Java Programming";

        String reversed = reverseString(input);

        System.out.println("Original String: " + input);
        System.out.println("Reversed String: " + reversed);
    }

    /**
     * Reverses a String by reading its UTF-16 code units
     * from the last index to the first.
     *
     * @param input the String to reverse
     * @return the reversed String
     * @throws IllegalArgumentException if input is null
     */
    public static String reverseString(String input) {

        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null");
        }

        StringBuilder reversed = new StringBuilder(input.length());

        // Read characters from the end of the String.
        for (int i = input.length() - 1; i >= 0; i--) {
            reversed.append(input.charAt(i));
        }

        return reversed.toString();
    }
}

Output

Original String: Java Programming
Reversed String: gnimmargorP avaJ

How Does the Program Work?

Step 1: Create a StringBuilder

StringBuilder reversed = new StringBuilder(input.length());

The StringBuilder class represents a mutable sequence of characters.

It allows characters to be appended without creating a new String object for every operation.

Passing input.length() to the constructor sets the initial capacity based on the input length. This avoids unnecessary buffer expansion for this example.

Step 2: Iterate from the Last Character

for (int i = input.length() - 1; i >= 0; i--) {
    reversed.append(input.charAt(i));
}

The loop starts at input.length() - 1, which is the index of the last character.

The value of i decreases after each iteration.

The charAt(i) method reads the character at the specified index, and append() adds it to the result.

For the input "Java", the loop processes the characters in this order:

a
v
a
J

Step 3: Convert the Result into a String

return reversed.toString();

The toString() method returns the reversed sequence as a new String.

When should you use this approach?

This approach is suitable for beginners and coding interviews when the task is to implement String reversal without calling reverse().

It is easy to understand and runs in linear time.

However, because it reverses individual UTF-16 code units, it is intended for basic text. Supplementary Unicode characters require a different approach, which I will cover later.

3. Reverse a String Using a Character Array and Two Pointers

Another efficient way to reverse a String is to convert it into a character array and swap characters from opposite ends.

This technique is known as the two-pointer approach.

The algorithm uses two indexes:

  • left starts at the beginning of the array.
  • right starts at the end of the array.

The program swaps the characters at these positions, moves both pointers toward the center, and repeats the process until they meet.

This approach does not require StringBuilder at all.

Java Program Using Two Pointers

public class ReverseStringUsingTwoPointers {

    public static void main(String[] args) {

        String input = "Java Programming";

        String reversed = reverseString(input);

        System.out.println("Original String: " + input);
        System.out.println("Reversed String: " + reversed);
    }

    /**
     * Reverses a String by swapping UTF-16 code units
     * in a character array.
     */
    public static String reverseString(String input) {

        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null");
        }

        // Convert the String into a mutable character array.
        char[] characters = input.toCharArray();

        int left = 0;
        int right = characters.length - 1;

        // Swap characters until the pointers meet.
        while (left < right) {

            char temporary = characters[left];

            characters[left] = characters[right];
            characters[right] = temporary;

            left++;
            right--;
        }

        // Create a new String from the reversed array.
        return new String(characters);
    }
}

Output

Original String: Java Programming
Reversed String: gnimmargorP avaJ

How Does the Two-Pointer Algorithm Work?

Consider the String "Java".

After converting it into a character array, the initial values are:

[J, a, v, a]

Step 1: Initialize Two Pointers

int left = 0;
int right = characters.length - 1;

The left pointer references the first character, while right references the last character.

Step 2: Swap the Characters

char temporary = characters[left];

characters[left] = characters[right];
characters[right] = temporary;

The temporary variable stores the character on the left so that it is not lost during the swap.

After the first swap, the array becomes:

[a, a, v, J]

Step 3: Move the Pointers

left++;
right--;

The left pointer moves one position forward, and the right pointer moves one position backward.

The program swaps the next pair of characters.

After the second swap, the array becomes:

[a, v, a, J]

At this point, the pointers have crossed, so the loop terminates.

Step 4: Create the Reversed String

return new String(characters);

The constructor creates a String from the reversed character array.

When should you use this approach?

The two-pointer technique is useful for learning array manipulation and in-place algorithms. It is also a popular coding interview technique.

The swaps occur inside the character array. However, converting the original String into an array still requires additional memory because Java Strings are immutable.

4. Reverse a Unicode String Without Using reverse()

Java Strings use UTF-16 encoding internally. Some Unicode characters, including many emojis, require two UTF-16 code units.

The previous examples reverse individual char values. This can separate the two code units that represent a supplementary Unicode character.

To avoid this problem, you can reverse complete Unicode code points using String.codePoints().

The following example reads code points from the end of an array and appends them to a new String.

Java Program Using Unicode Code Points

public class ReverseUnicodeString {

    public static void main(String[] args) {

        String input = "Java 😀 Programming";

        String reversed = reverseString(input);

        System.out.println("Original String: " + input);
        System.out.println("Reversed String: " + reversed);
    }

    /**
     * Reverses the order of Unicode code points without
     * using StringBuilder.reverse().
     */
    public static String reverseString(String input) {

        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null");
        }

        // Convert the String into complete Unicode code points.
        int[] codePoints = input.codePoints().toArray();

        StringBuilder reversed = new StringBuilder(input.length());

        // Append Unicode code points in reverse order.
        for (int i = codePoints.length - 1; i >= 0; i--) {
            reversed.appendCodePoint(codePoints[i]);
        }

        return reversed.toString();
    }
}

Output

Original String: Java 😀 Programming
Reversed String: gnimmargorP 😀 avaJ

Explanation

The statement:

int[] codePoints = input.codePoints().toArray();

converts the String into an array of Unicode code points.

The program then loops through this array in reverse order:

for (int i = codePoints.length - 1; i >= 0; i--) {
    reversed.appendCodePoint(codePoints[i]);
}

The appendCodePoint() method appends the complete UTF-16 representation of each Unicode code point.

This prevents valid surrogate pairs from being split during reversal.

Important: A user-perceived character can contain multiple Unicode code points. Some family emojis, skin-tone variants, and combining-character sequences fall into this category. Reversing code points does not necessarily preserve these complete visual characters. Applications requiring that behavior need grapheme-cluster-aware text processing.

5. Comparing Different String Reversal Approaches

All three approaches reverse the order of characters or code points, but they use different techniques.

Approach Time Complexity Space Complexity Best Use Case
For Loop with StringBuilder O(n) O(n) Beginner-level String reversal
Two Pointers O(n) O(n) Array manipulation and interviews
Unicode Code Points O(n) O(n) Supplementary Unicode characters

Here, n represents the length of the input String.

Each approach processes the input in linear time and requires additional memory to create the reversed result.

The two-pointer method performs swaps inside the character array, but the array itself must be created from the immutable String.

The Unicode approach also allocates an integer array to store code points before reversing them.

6. How to Run the Java Programs

You can run these programs in IntelliJ IDEA, Eclipse, VS Code, or directly from the command line.

All examples work with Java 17 or later and use only the Java standard library.

Step 1: Create the Java File

Create a file named ReverseStringUsingLoop.java.

Copy the complete code from the first example into the file.

Step 2: Compile the Program

Open a terminal in the directory containing the file and run:

javac ReverseStringUsingLoop.java

Step 3: Run the Program

java ReverseStringUsingLoop

The program displays the original and reversed Strings.

To run another example, save its code in a separate file whose filename matches the public class name.

7. Common Mistakes When Reversing a String in Java

1. Using Incorrect Loop Boundaries

The last valid index in a String is length() - 1.

Starting a reverse loop at length() causes a StringIndexOutOfBoundsException.

Use:

for (int i = input.length() - 1; i >= 0; i--) {
    // Process the character at index i.
}

2. Using String Concatenation Inside a Loop

A beginner might write:

String reversed = "";

for (int i = input.length() - 1; i >= 0; i--) {
    reversed += input.charAt(i);
}

This can produce the correct result for basic text, but repeated String concatenation may create many temporary objects.

For longer inputs, use a StringBuilder or character array to avoid unnecessary allocations.

3. Assuming Strings Are Mutable

Java Strings cannot be modified after creation.

Methods that reverse Strings create new results rather than changing the original String.

4. Ignoring Empty Strings

An empty String should produce another empty String.

The examples handle this naturally because their loops have no characters to process.

5. Forgetting About Null Input

Calling methods on a null reference causes a NullPointerException.

For reusable methods, validate input and define how null values should be handled.

6. Reversing Unicode Characters Incorrectly

Reversing individual UTF-16 code units can split supplementary Unicode characters.

Use String.codePoints() when you need code-point-aware reversal.

8. Frequently Asked Questions

How do you reverse a String in Java without using reverse()?

Use a for loop that starts at the last character of the String and moves toward the first. Append the characters to a new StringBuilder or store them in an array.

Can I reverse a String without using StringBuilder?

Yes. Convert the String into a character array and use two pointers to swap characters from opposite ends. Then create a new String from the reversed array.

Which approach is best for Java coding interviews?

The two-pointer approach is useful because it demonstrates array manipulation, index management, and efficient algorithms.

The reverse-loop approach is also a good choice when an interview focuses on basic String operations.

What is the time complexity of reversing a String?

The loop-based and two-pointer approaches have O(n) time complexity, where n is the input length.

They also require O(n) additional memory when reversing an immutable Java String.

Does reversing a String change the original String?

No. Java Strings are immutable. The reversal operation creates a new String, leaving the original input unchanged.

Can I reverse a String containing emojis?

Yes. Use String.codePoints() to process supplementary Unicode characters without splitting surrogate pairs.

For complex emoji sequences containing multiple code points, complete grapheme-cluster processing may be necessary.

Can I reverse a String using recursion?

Yes. A recursive method can reverse a String by processing characters from the end toward the beginning.

However, recursion requires additional stack space and may cause a StackOverflowError for sufficiently long Strings. An iterative solution is generally more practical.

Conclusion

In this tutorial, you learned how to reverse a String in Java without using StringBuilder.reverse().

The first approach uses a for loop to read characters from the end of the String and append them to a new result. It is simple and suitable for beginners.

The second approach uses a character array and two pointers. It reverses the array by swapping characters from opposite ends. This technique is useful for understanding array manipulation and solving coding interview problems.

You also learned how to reverse Unicode code points without splitting valid surrogate pairs. This is important when working with text that contains supplementary Unicode characters.

For basic String reversal without a built-in reverse method, I recommend starting with the two-pointer approach. It provides a clear understanding of the reversal algorithm and can be adapted to other array-processing problems.

As a next step, try writing a Java program to reverse only the words in a sentence while preserving their original order. This is another useful String coding interview problem that builds on the same concepts.

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments