Reverse a String in Java: Step-by-Step Guide | Updated 2025

Reverse a String in Java: Stepwise Methods and Examples

CyberSecurity Framework and Implementation article ACTE

About author

Priya (Web Developer )

Priya is a Java programming instructor who focuses on algorithmic foundations and string manipulation, particularly the use of various techniques to reverse strings. Her knowledge of character arrays, stack-based logic, iterative loops, and StringBuilder.reverse() allows her to teach how to efficiently reverse strings while managing edge cases.

Last updated on 15th Sep 2025| 10693

(5.0) | 32961 Ratings

Introduction to String Manipulation

String manipulation is a fundamental part of Java programming, involving operations such as searching, replacing, formatting, trimming, and reversing. Java’s String class, being immutable, offers various methods for safe and efficient manipulation. Among the most common tasks is reverse a string in Java, which forms the basis of many interview questions and algorithmic exercises. To complement such string-handling techniques with practical development expertise, exploring Web Developer Training equips learners to master string operations, DOM manipulation, and user input handling in JavaScript building interactive web applications with clean, efficient logic. Understanding multiple ways to reverse a string helps strengthen your logical reasoning and deepens your familiarity with Java APIs and control structures.


To Earn Your Web Developer Certification, Gain Insights From Leading Data Science Experts And Advance Your Career With ACTE’s Web Developer Courses Today!


What Does Reverse a String in Java Mean?

Reversing a string means reordering its characters from the last to the first. For example, reversing “hello” results in “olleh”. In programming terms, this involves changing the character at position i with the character at position length – i – 1. This operation is foundational and commonly used in tasks such as palindrome checking, encryption, and string formatting.

    Subscribe To Contact Course Advisor

    Using for Loop to Reverse a String in Java

    A straightforward method to reverse a string is by using a for loop to iterate through the characters from the end to the beginning.

    Example:

    • String str = “Java”;
    • String reversed = “”;
    • for (int i = str.length() – 1; i >= 0; i–) {
    • reversed += str.charAt(i);
    • }
    • System.out.println(reversed); // Output: avaJ

    While this method is easy to understand, using + for concatenation repeatedly creates new string objects (because of string immutability), which may lead to inefficient memory use for long strings.


    Would You Like to Know More About Web Developer? Sign Up For Our Web Developer Courses Now!


    Using StringBuilder and StringBuffer

    Java provides two mutable string classes StringBuilder and StringBuffer both of which include a convenient reverse() method.

    Using StringBuilder:

    • String input = “OpenAI”;
    • StringBuilder sb = new StringBuilder(input);
    • System.out.println(sb.reverse()); // Output: IAnepO

    Using StringBuffer:

    • StringBuffer sbf = new StringBuffer(“ReverseMe”);
    • System.out.println(sbf.reverse()); // Output: eMesreveR

    StringBuilder is faster and preferred in single-threaded contexts, while StringBuffer is thread-safe and suitable for multi-threaded applications.

    Course Curriculum

    Develop Your Skills with Web Developer Certification Course

    Weekday / Weekend BatchesSee Batch Details

    Using Recursion to Reverse a String

    Recursion is another elegant way to reverse a string, though it may be less efficient for very large inputs due to stack usage.

    Recursive Method:

    • public static String reverseRecursive(String str) {
    • if (str == null || str.length() <= 1) {
    • return str;
    • }
    • return reverseRecursive(str.substring(1)) + str.charAt(0);
    • }

    This technique demonstrates recursion concepts well but should be used cautiously due to the overhead of multiple substring creations and recursive calls.


    Are You Interested in Learning More About Web Developer? Sign Up For Our Web Developer Courses Today!


    Converting String to Char Array for Reversal

    You can convert a string into a character array and manually reverse it by swapping elements. To complement such low-level string manipulation techniques with full-stack development expertise, exploring Web Developer Training equips learners to handle string operations, DOM updates, and user-driven events in JavaScript building interactive web applications with clean logic and responsive behavior.

    Example:

    • String str = “Data”;
    • char[] chars = str.toCharArray();
    • for (int i = 0, j = chars.length – 1; i < j; i++, j–) {
    • char temp = chars[i];
    • chars[i] = chars[j];
    • chars[j] = temp;
    • }
    • System.out.println(new String(chars)); // Output: ataD

    This method is efficient and gives better control over the reversal process. It also avoids creating multiple new objects.

    Web Development Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    Using Collections Framework for Reversal

    Though less common, Java’s Collections Framework can be used by converting the string to a list of characters.

    • String str = “Example”;
    • List<Character> charList = new ArrayList<>();
    • for (char c : str.toCharArray()) {
    • charList.add(c);
    • }
    • Collections.reverse(charList);
    • StringBuilder result = new StringBuilder();
    • for (char c : charList) {
    • result.append(c);
    • }
    • System.out.println(result.toString()); // Output: elpmaxE

    While this approach is more verbose and less performant, it demonstrates the flexibility of Java’s collections for string manipulation.

    Reversing Words in a Sentence (Split Approach)

    Sometimes you may want to reverse only the words in a sentence, not the characters.

    Example:

    • String sentence = “Java is powerful”;
    • String[] words = sentence.split(” “);
    • StringBuilder reversedSentence = new StringBuilder();
    • for (int i = words.length – 1; i >= 0; i–) {
    • reversedSentence.append(words[i]).append(” “);
    • }
    • System.out.println(reversedSentence.toString().trim());
    • // Output: powerful is Java

    This technique is useful in natural language processing, chat applications, or sentence transformation tasks.


    Handling Null and Edge Cases

    Virtual Function

    Before reversing a string, it’s important to handle null and edge cases to avoid unexpected behavior.

    Consider the following:

    • Null String: Null input should not cause a NullPointerException.
    • Empty String: Should return empty.
    • Single-Character String: Return as is.
    • Safe Approach: Always validate input before processing.
    • public static String safeReverse(String str) {
    • if (str == null) return null;
    • if (str.length() <= 1) return str;
    • return new StringBuilder(str).reverse().toString();
    • }

    By validating input, you ensure that your reversal logic is robust and production-ready.


    Performance Considerations

    When reversing strings, it’s crucial to pick the right technique for speed and efficiency. String concatenation in loops can be inefficient because it creates multiple objects, leading to O(n²) time complexity. For larger inputs, it’s better to use StringBuilder or StringBuffer methods since they are designed for better performance. Swapping characters in a char array is also memory-efficient and quick, working at O(n) time. However, a recursive approach might cause a stack overflow with very large strings, which can cause issues. In most real-world cases, the best options are the StringBuilder.reverse() method or character array techniques. Both methods effectively balance simplicity and efficiency, making them great choices for reversing strings.


    Common Interview Questions

    Reversing strings is a popular topic in Java interviews. Some frequently asked variations include:

    • Reverse a string without using built-in methods.
    • Reverse a sentence word-by-word.
    • Check if a string is a palindrome using reversal.
    • Reverse only vowels in a string.
    • Reverse every k characters in a string.
    • Reverse string using stack or recursion.

    These questions test not just your string manipulation skills but also your understanding of time complexity, data structures, and control flow.


    Best practices

    • Use StringBuilder.reverse() for most cases clean and efficient.
    • Validate input for null and empty cases.
    • Avoid using + in loops for long strings and prefer StringBuilder.
    • Choose recursion only when suitable and safe.
    • Practice edge cases and sentence-based variations for interviews.

    Summary

    Reverse a String in Java is a basic but important task in Java programming. There are several ways to do this, each with its advantages and disadvantages. One common method is using loops. You can go through the string from the end to the beginning, building the reversed string character by character.Another option is recursion, which can offer a more elegant solution by breaking the problem into smaller parts. However, it might be less efficient for very long strings because of the risk of stack overflow. For convenience, Java also has the StringBuilder class. To complement such string manipulation strategies with practical development skills, exploring Web Developer Training equips learners to handle recursive logic, optimize performance, and implement efficient string operations in JavaScript and modern web frameworks. This class includes a built-in method to reverse strings quickly and efficiently.

    Upcoming Batches

    Name Date Details
    Web Developer Certification Course

    15 - Sep- 2025

    (Weekdays) Weekdays Regular

    View Details
    Web Developer Certification Course

    17 - Sep - 2025

    (Weekdays) Weekdays Regular

    View Details
    Web Developer Certification Course

    20 - Sep - 2025

    (Weekends) Weekend Regular

    View Details
    Web Developer Certification Course

    21 - Sep - 2025

    (Weekends) Weekend Fasttrack

    View Details