View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Reverse a String in Java – 10 Efficient Ways with Examples

Updated on 12/05/20257,739 Views

Reversing a string simply means flipping its characters so the last character becomes the first, and so on. This is a popular problem in Java programming, often seen in coding interviews, algorithm challenges, and data transformation tasks.

It's not just a basic programming exercise but also a great way to explore core Java concepts like strings, loops, recursion, arrays, and data structures. In this blog, we’ll walk through 11 efficient ways to reverse a string in Java, complete with working code, output, and explanations.

Whether you're a beginner learning Java or someone brushing up before an interview, this guide has you covered. Software engineering courses can help you master Java basics and core concepts faster.

What is String Reversal in Java?

In Java, string reversal is the process of rearranging the characters of a string in reverse order. For instance, reversing "Java" gives "avaJ". It’s commonly used in interview questions to test logic-building and understanding of strings.

Java strings are immutable, meaning you can’t change them after creation. That’s why most string reversal techniques create a new string or use mutable classes like StringBuilder.

1. Using String Concatenation (Creating a New String)

This method uses a loop to traverse the string from the end to the beginning, appending each character to a new string. It’s simple but inefficient due to the immutability of strings, which creates a new string each time, making it slow for large strings.

Best for: Beginners or quick logic checks.

public class ReverseString1 {
    public static void main(String[] args) {
        String input = "Java";
        String reversed = "";
        for (int i = input.length() - 1; i >= 0; i--) {
            reversed += input.charAt(i);
        }
        System.out.println(reversed);
    }
}

Output:

avaJ

Explanation: We loop through the string in reverse and append each character to a new string.

Sharpen your expertise by enrolling in these recommended courses.

2. Using StringBuilder’s reverse() Method

StringBuilder is a mutable object, making it an ideal choice for string manipulation. Using its reverse() method, you can reverse a string in a single line. This approach is fast, simple, and works well for most scenarios, especially when you need efficiency and readability.

Best for: Beginners and interview scenarios.

public class ReverseString2 {
    public static void main(String[] args) {
        String input = "OpenAI";
        StringBuilder sb = new StringBuilder(input);
        System.out.println(sb.reverse());
    }
}

Output:

IAnepO

Explanation: StringBuilder.reverse() directly reverses the string in one line using an internal char array.

Must explore: StringBuffer and StringBuilder Difference in Java

3. Using StringBuffer’s reverse() Method

Similar to StringBuilder, StringBuffer offers the reverse() method but with the added benefit of thread safety. If multiple threads need to manipulate the string concurrently, StringBuffer is a better option. Otherwise, StringBuilder is often preferred for better performance in single-threaded environments.

Best for: Thread-safe applications.

public class ReverseString3 {
    public static void main(String[] args) {
        String input = "Code";
        StringBuffer sb = new StringBuffer(input);
        System.out.println(sb.reverse());
    }
}

Output:

edoC

Explanation: Works just like StringBuilder, but ensures thread safety for concurrent tasks.

Also explore: Strings in Java Vs Strings in Cpp

4. Using a Char Array and Swapping Characters

This method manually reverses a string by converting it to a character array and swapping characters from both ends. It’s memory-efficient since it doesn’t create new strings but rather manipulates the array in-place. It’s a good option for optimizing space in larger strings.

Best for: Memory efficiency and in-place logic.

public class ReverseString4 {
    public static void main(String[] args) {
        String input = "Hello";
        char[] chars = input.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:

olleH

Explanation: This approach reverses the characters in-place using a temporary variable for swapping.

Must check: Char array to string in Java

5. Using a List and Collections.reverse()

In this approach, you convert the string to a list of characters, then use Collections.reverse() to reverse the list. While it’s easy to implement and demonstrates the use of collections, it’s not the most efficient method due to extra memory usage for storing the list.

Best for: Demonstrating collection manipulation.

import java.util.*;

public class ReverseString5 {
    public static void main(String[] args) {
        String input = "World";
        List<Character> charList = new ArrayList<>();

        for (char c : input.toCharArray()) {
            charList.add(c);
        }

        Collections.reverse(charList);

        for (char c : charList) {
            System.out.print(c);
        }
    }
}

Output:

dlroW

Explanation: We convert the string to a character list, reverse it, and print each character.

6. Using a Stack (LIFO)

A stack follows the Last In First Out (LIFO) principle. By pushing each character of the string onto a stack and then popping it off, you can reverse the string. This method illustrates the stack data structure but is less efficient due to extra space used by the stack.

Best for: Learning data structure behavior.

import java.util.*;

public class ReverseString6 {
    public static void main(String[] args) {
        String input = "Stack";
        Stack<Character> stack = new Stack<>();

        for (char c : input.toCharArray()) {
            stack.push(c);
        }

        while (!stack.isEmpty()) {
            System.out.print(stack.pop());
        }
    }
}

Output:

kcatS

Explanation: Characters are pushed into a stack and popped in reverse order to form the output.

7. Using Recursion

Recursion in Java,  works by breaking down the problem into smaller parts and reversing them step by step. It’s elegant and demonstrates recursion but isn’t ideal for large strings. The risk of stack overflow arises with long strings, so it’s more of an educational approach than a practical one.

Best for: Understanding recursion, not large strings.

public class ReverseString7 {
    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("Recursion"));
    }
}

Output:

noisruceR

Explanation: This function repeatedly removes the first character and adds it at the end recursively.

8. Using a Byte Array

Converting the string to a byte array allows manipulation at the byte level. The string is reversed by rearranging the bytes, and the result is returned as a new string. It’s a good method for handling data at a lower level but doesn’t offer significant performance benefits over others.

Best for: Byte-level operations.

public class ReverseString8 {
    public static void main(String[] args) {
        String input = "Byte";
        byte[] strAsByteArray = input.getBytes();
        byte[] result = new byte[strAsByteArray.length];

        for (int i = 0; i < strAsByteArray.length; i++) {
            result[i] = strAsByteArray[strAsByteArray.length - i - 1];
        }

        System.out.println(new String(result));
    }
}

Output:

etyB

Explanation: Each byte is stored in reverse order in a new byte array and converted back to a string.

9. Using XOR Operation to Swap Without Temp Variable

The XOR swap method allows reversing characters without an auxiliary variable. By using XOR operations, you swap characters in-place. While it’s an interesting and efficient technique in terms of memory usage, it’s more academic and rarely used in real-world applications due to its complexity and reduced readability.

Best for: Bit manipulation interviews.

public class ReverseString9 {
    public static void main(String[] args) {
        String input = "Bitwise";
        char[] arr = input.toCharArray();
        int i = 0, j = arr.length - 1;

        while (i < j) {
            arr[i] ^= arr[j];
            arr[j] ^= arr[i];
            arr[i] ^= arr[j];
            i++;
            j--;
        }

        System.out.println(new String(arr));
    }
}

Output:

esiwtiB

Explanation: XOR swaps two characters without using a temp variable, reversing the string in-place.

10. Using Java 8 Streams API

The Java 8 Streams API introduces a functional style of programming. Using streams, characters are processed, reversed, and collected in a new string. This method is modern, concise, and works well in environments that prioritize functional programming but might be overkill for simpler use cases.

Best for: Writing clean, Java 8+ compatible code.

import java.util.stream.*;

public class ReverseString10 {
    public static void main(String[] args) {
        String input = "Stream";
        String reversed = IntStream.rangeClosed(1, input.length())
            .mapToObj(i -> input.charAt(input.length() - i))
            .map(String::valueOf)
            .collect(Collectors.joining());
        System.out.println(reversed);
    }
}

Output:

maertS

Explanation: Java Streams reverse the characters using range and collector in a concise one-liner.

Performance Comparison of All Methods

Each method has its pros and cons. Here’s a quick comparison:

Method

Time Complexity

Space Complexity

Notes

String Concatenation

O(n²)

O(n)

Inefficient due to immutability

StringBuilder.reverse()

O(n)

O(n)

Most efficient and simple

StringBuffer.reverse()

O(n)

O(n)

Thread-safe

Char Array Swap

O(n)

O(n)

In-place, efficient

Collections.reverse()

O(n)

O(n)

More verbose

Stack

O(n)

O(n)

LIFO logic demonstration

Recursion

O(n)

O(n)

Stack Overflow risk

Byte Array

O(n)

O(n)

Byte-level demo

XOR Swapping

O(n)

O(n)

Tricky but efficient

Java 8 Streams

O(n)

O(n)

Clean, modern

Conclusion

We explored different ways to reverse a string in Java, from simple loops and arrays to recursion, streams, and even bitwise operations. Each method offers something unique — from simplicity to performance to learning data structures.

Choose a method based on your use case: readability, speed, or memory optimization. String reversal isn’t just an interview question — it’s a gateway into deeper Java programming concepts.

FAQs

1. Can we reverse a string without using any built-in methods in Java?

Yes, you can reverse a string manually using loops and character arrays. This approach involves iterating over the string from the end to the start and appending characters to form a new string without relying on Java's built-in methods like reverse().

2. Why is String immutable in Java?

String in Java is immutable for security, thread-safety, and performance reasons. Once created, a string's value cannot be changed, which helps avoid unexpected bugs, especially in multithreaded environments or while working with sensitive data like URLs, passwords, or file paths.

3. What is the difference between StringBuilder and StringBuffer?

Both are mutable classes for string manipulation. StringBuilder is faster but not thread-safe, making it suitable for single-threaded tasks. StringBuffer is thread-safe due to synchronized methods, so it’s preferred when multiple threads might access or modify the same string object.

4. When should I avoid using recursion for string reversal?

Avoid recursion when dealing with long strings, as it can lead to StackOverflowError. Recursion consumes additional stack memory for each call, making it less efficient and riskier for large-scale string processing compared to iterative methods or built-in functions.

5. How does using a stack help in reversing a string?

A stack follows the Last-In-First-Out (LIFO) order. When you push characters of a string onto the stack and then pop them, the characters come out in reverse order. It’s a great way to understand stack operations, though not the most memory-efficient.

6. Is reversing a string an in-place operation?

It depends on the method. If you use character arrays and swap characters from both ends, it's in-place. However, methods involving new strings or data structures like StringBuilder, lists, or stacks are not in-place as they require extra memory allocation.

7. Can I reverse a string using Java 8 features only?

Yes, Java 8 introduced the Streams API, which allows you to reverse a string using streams, Collectors.joining(), and String.chars() or String.codePoints(). It’s a functional programming approach and works well when readability and modern syntax are priorities.

8. Does reversing a string change the original string?

No, strings in Java are immutable. Any method that appears to reverse a string actually returns a new string. The original string remains unchanged unless you’re using mutable classes like StringBuilder or working directly with character arrays.

9. What is the time complexity of different string reversal methods?

Most methods like StringBuilder.reverse(), loops, and character swapping have O(n) time complexity. Stack and recursion-based approaches also run in O(n) time but may use extra space, affecting space complexity. Byte array and XOR swap methods also follow O(n) time.

10. Is reversing a Unicode string different from a regular string?

Yes, Unicode characters may span more than one char in Java due to surrogate pairs. Standard reversal using char[] or StringBuilder might break such characters. Use codePointAt() and codePoints() to safely reverse strings containing Unicode characters like emojis or special symbols.

11. Can I reverse a string in place using XOR?

Yes, XOR can be used to swap characters in-place without a temporary variable. It works at the bit level and can reverse a string efficiently. However, it’s complex and not readable, so it’s mainly used in academic contexts or competitive programming.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.