Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program to print the given string in reverse?

The simplest way to print a string in reverse in Java is to wrap it in a StringBuilder and call reverse(): new StringBuilder(str).reverse().toString(). Because a String is immutable you cannot reverse it in place, so every technique builds a new sequence of characters. Beyond the one-liner you can convert the string to a char array and swap from both ends with two pointers, loop from the last index while appending each character, or solve it with recursion.

Why String Immutability Matters

In Java, a String object can never be changed after it is created. Methods like substring() or concat() do not mutate the original; they return a brand new String. That is why you cannot "reverse the string itself" and instead build a new one. It is also why concatenating characters with += inside a loop is wasteful: each iteration allocates a fresh String, giving O(n^2) behavior. Using a StringBuilder (or its thread-safe sibling StringBuffer) avoids that overhead by mutating a single internal buffer.

Approach 1 - StringBuilder.reverse()

This is the cleanest and fastest approach to write. Key points:

  • One call: Wrap the string in a StringBuilder, call reverse(), then convert back with toString().
  • Thread safety: Swap StringBuilder for StringBuffer if the buffer is shared across threads.
  • Complexity: O(n) time and O(n) space, since it allocates one new character buffer.
public class ReverseString {
    public static void main(String[] args) {
        String str = "LambdaTest";
        String reversed = new StringBuilder(str).reverse().toString();
        System.out.println("Original: " + str);
        System.out.println("Reversed: " + reversed);
    }
}

Output:

Original: LambdaTest
Reversed: tseTadbmaL

Approach 2 - Char Array With a Two-Pointer Swap

When you want to see the underlying algorithm, swap characters in place on a char array. Key points:

  • Convert first: Call toCharArray() because the String itself is immutable.
  • Two pointers: Exchange the characters at left and right, then move both pointers inward until they meet.
  • Complexity: O(n) time with O(n) space for the array, and no per-character String allocation.
public class ReverseTwoPointer {
    public static void main(String[] args) {
        String str = "LambdaTest";
        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));
    }
}

Output:

tseTadbmaL

Approach 3 - Loop Building the String Backwards

Iterating from the last character to the first is the most explicit version and is easy to extend with custom logic. Key points:

  • Reverse iteration: Loop with the index running from str.length() - 1 down to 0.
  • Append, don't concatenate: Use a StringBuilder inside the loop; concatenating a String each iteration is O(n^2).
  • Extend easily: Add filtering or case changes inside the loop when you need more than a plain reverse.
public class ReverseLoop {
    public static void main(String[] args) {
        String str = "LambdaTest";
        StringBuilder rev = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            rev.append(str.charAt(i));
        }
        System.out.println(rev.toString());
    }
}

Output:

tseTadbmaL

Approach 4 - Recursion

Recursion gives an elegant, concise solution that is popular in interviews. Key points:

  • Base case: An empty string returns itself, which stops the recursion.
  • Recursive case: Reverse the substring from index 1, then append the first character at the end.
  • Watch the stack: It uses O(n) call-stack depth, so very long strings can trigger a StackOverflowError.
public class ReverseRecursion {
    public static String reverse(String str) {
        if (str.isEmpty()) {
            return str;
        }
        return reverse(str.substring(1)) + str.charAt(0);
    }

    public static void main(String[] args) {
        System.out.println(reverse("LambdaTest"));
    }
}

Output:

tseTadbmaL

Reversing Words Instead of Characters

Reversing characters turns "Hello World" into "dlroW olleH". A common follow-up is to reverse the order of words while keeping each word readable. Split on whitespace, walk the array backwards, and join the words with spaces.

public class ReverseWords {
    public static void main(String[] args) {
        String sentence = "Test on real devices with LambdaTest";
        String[] words = sentence.split(" ");
        StringBuilder result = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            result.append(words[i]);
            if (i > 0) {
                result.append(" ");
            }
        }
        System.out.println(result.toString());
    }
}

Output:

LambdaTest with devices real on Test

Which Approach Should You Use?

ApproachTimeSpaceUse when
StringBuilder.reverse()O(n)O(n)Default; cleanest and fastest to write.
char[] two-pointerO(n)O(n)You want explicit control or to learn the algorithm.
Loop + StringBuilderO(n)O(n)You need custom logic while reversing.
RecursionO(n)O(n) stackTeaching recursion; avoid for very long input.
Reverse wordsO(n)O(n)You need word order reversed, not characters.

String utilities like these often sit inside larger automation suites. If your Java or Selenium tests assert on reversed or formatted strings, you can run them across thousands of browser and OS combinations on the Selenium Automation cloud to confirm the behavior is consistent everywhere.

Frequently Asked Questions

What is the simplest way to reverse a string in Java?

Wrap the string in a StringBuilder and call reverse(): new StringBuilder(str).reverse().toString(). It is one line, runs in O(n) time, and is the approach most Java developers reach for first.

Can you reverse a String in place in Java?

No. String is immutable, so its internal characters cannot be modified. To swap characters in place you must first convert the string to a char array with toCharArray(), reverse that array, then build a new String from it.

How do you reverse a string without StringBuilder?

Use a char array with a two-pointer swap, iterate the string backwards with a for loop, or use recursion. All three avoid StringBuilder.reverse() while still producing the reversed string in linear time.

What is the time complexity of reversing a string?

Every standard approach runs in O(n) time because each character is visited once, and they use O(n) extra space for the new string or array. Recursion additionally consumes O(n) call-stack depth, which can overflow on very long inputs.

How do you reverse the order of words instead of characters?

Split the sentence on whitespace with split(" "), iterate the resulting array from the last element to the first, and join the words back with spaces. This reverses word order while keeping each word readable, unlike character reversal.

Does StringBuilder.reverse() handle Unicode correctly?

For surrogate pairs, yes. StringBuilder.reverse() keeps high and low surrogates together, so most emoji and supplementary characters reverse safely. Sequences built from combining characters can still render unexpectedly, but the underlying code points are not corrupted.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests