The function takes the first character of a String - str.charAt(0) - puts it at the end and then calls itself - reverse() - on the remainder - str.substring(1), adding these two things together to get its result - reverse(str.substring(1)) + str.charAt(0)

When the passed in String is one character or less and so there will be no remainder left - when str.length() <= 1) - it stops calling itself recursively and just returns the String passed in.

So it runs as follows:

reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
"olleH"
Answer from David Webb on Stack Overflow
Top answer
1 of 16
104

The function takes the first character of a String - str.charAt(0) - puts it at the end and then calls itself - reverse() - on the remainder - str.substring(1), adding these two things together to get its result - reverse(str.substring(1)) + str.charAt(0)

When the passed in String is one character or less and so there will be no remainder left - when str.length() <= 1) - it stops calling itself recursively and just returns the String passed in.

So it runs as follows:

reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
"olleH"
2 of 16
20

You need to remember that you won't have just one call - you'll have nested calls. So when the "most highly nested" call returns immediately (when it finds just "o"), the next level up will take str.charAt(0) - where str is "lo" at that point. So that will return "ol".

Then the next level will receive "ol", execute str.charAt(0) for its value of str (which is "llo"), returning "oll" to the next level out.

Then the next level will receive the "oll" from its recursive call, execute str.charAt(0) for its value of str (which is "ello"), returning "olle" to the next level out.

Then the final level will receive the "oll" from its recursive call, execute str.charAt(0) for its value of str (which is "hello"), returning "olleh" to the original caller.

It may make sense to think of the stack as you go:

// Most deeply nested call first...
reverse("o") -> returns "o"
reverse("lo") -> adds 'l', returns "ol" 
reverse("llo") -> adds 'l', returns "oll" 
reverse("ello") -> adds 'e', returns "olle" 
reverse("hello") -> adds 'h', returns "olleh" 
🌐
Reddit
reddit.com › r/learnprogramming › explanation for how this recursive method to reverse a string works (java)
r/learnprogramming on Reddit: Explanation for how this recursive method to reverse a string works (JAVA)
February 21, 2021 -
public String reverse(String str) {
    if(str.length()==0){
        return str;
    }
    else{
        return reverse(str.substring(1))+str.charAt(0);
    }
}

I was wondering how recursive methods work. What causes this method continue to plug itself back into the function? When does str.length==0 and why does it end up returning a reversed string rather than a blank in my main method.

Discussions

recursion - Whats the best way to recursively reverse a string in Java? - Stack Overflow
Basically use recursion in situations where you definitely need it. 2014-12-31T19:46:46.107Z+00:00 ... If you're going to do this, you want to operate on a character array, because a String is immutable and you're going to be copying Strings all over the place if you do it that way. This is untested and totally stream of consciousness. It probably has an OB1 somewhere. And very not-Java. public String reverseString... More on stackoverflow.com
🌐 stackoverflow.com
Explanation for how this recursive method to reverse a string works (JAVA)
Try walking through it on paper. Here's an algorithm to follow: Reverse: input is "str". If str is blank, return blank. separate str into the first character, car, and the remaining characters, cdr. Invoke this algorithm with an input of cdr, label result "reversedCdr". Return reversedCdr + car. If you do this by hand, you'll see what's happening. Make sure to carefully track the stack. Here's an example. Reverse(str is "nab") str isn't blank, keep going car is "n", cdr is "ab". Call reverse(str is "ab") str isn't blank, keep going car is "a", cdr is "b" Call reverse(str is "a") str isn't blank, keep going car is "b", cdr is "" Call reverse(str is "") str is blank, return blank. Return "" + "b", "b" Return "b" + "a", "ba" Return "ba" + "n", "ban" More on reddit.com
🌐 r/learnprogramming
3
5
February 21, 2021
Trying to reverse a string using recursion, why is my program not working?
If you are trying to do recursion then you want to have a return. Each step in the recursive process should do one unit of work. After the one unit of work is done, it should examine the data to see if it's done. If it is done, return. If it isn't done recurse. Here's an example in PHP: public function reverseString($input) { // Get the last character in the list/array/string $last_char = $input[strlen($input) - 1]; // Compute the remaining list/array/string $new_input = substr($input, 0, -1); // If the new list/array/string is empty, we are done so we return our result // Else return our result concatenated with the next result if (strlen($new_input) == 0) { return $last_char; } else { return $last_char . $this->reverseString($new_input); } } More on reddit.com
🌐 r/AskComputerScience
17
16
February 28, 2020
Reverse a sentence using recursion
It works to reverse the sentence, because of the order of two inner lines of reverseSentence().eg, if printf was called before recursing, then the sentence would print out in-order. Because the order is to recurse first, then printf, the first character captured is the last to be printed to the screen. More on reddit.com
🌐 r/C_Programming
6
2
September 26, 2022
🌐
How to do in Java
howtodoinjava.com › home › string › reverse all characters of a string in java
Reverse All Characters of a String in Java
January 10, 2023 - Perform the above operation, recursively, until the string ends · public class ReverseString { public static void main(String[] args) { String blogName = "How To Do In Java"; String reverseString = reverseString(blogName); Assertions.assertEquals("avaJ nI oD oT woH", reverseString); } public static String reverseString(String string) { if (string.isEmpty()) { return string; } return reverseString(string.substring(1)) + string.charAt(0); } }
🌐
BeginnersBook
beginnersbook.com › 2017 › 09 › java-program-to-reverse-a-string-using-recursion
Java Program to Reverse a String using Recursion
September 8, 2017 - public class JavaExample { public static void main(String[] args) { String str = "Welcome to Beginnersbook"; String reversed = reverseString(str); System.out.println("The reversed string is: " + reversed); } public static String reverseString(String str) { if (str.isEmpty()) return str; //Calling Function Recursively return reverseString(str.substring(1)) + str.charAt(0); } } ... import java.util.Scanner; public class JavaExample { public static void main(String[] args) { String str; System.out.println("Enter your username: "); Scanner scanner = new Scanner(System.in); str = scanner.nextLine(); scanner.close(); String reversed = reverseString(str); System.out.println("The reversed string is: " + reversed); } public static String reverseString(String str) { if (str.isEmpty()) return str; //Calling Function Recursively return reverseString(str.substring(1)) + str.charAt(0); } }
🌐
TutorialsPoint
tutorialspoint.com › Java-program-to-reverse-a-string-using-recursion
Java program to reverse a string using recursion
June 5, 2025 - In the above program, the StringReverse class, the reverseString method checks if the string is empty. If not, it calls itself with the substring starting from the second character. This recursive process continues until an empty string is reached, forming the base case.
🌐
Open Tech Guides
opentechguides.com › how-to › article › java › 90 › string-reverse-recursion.html
Reverse a string using recursion in Java - Open Tech Guides
This function recursively calls itself until the length of the parameter string equals 1. Each function call removes and returns the first character of the argument string. The reverseString() function can be better explained with an example. Let's say the input string is star.
Find elsewhere
🌐
Guru99
guru99.com › home › java tutorials › how to reverse a string in java using recursion
How to Reverse a String in Java using Recursion
December 30, 2023 - package com.guru99; public class ReverseString { public static void main(String[] args) { String myStr = "Guru99"; //create Method and pass and input parameter string String reversed = reverseString(myStr); System.out.println("The reversed string is: " + reversed); } //Method take string parameter and check string is empty or not public static String reverseString(String myStr) { if (myStr.isEmpty()){ System.out.println("String in now Empty"); return myStr; } //Calling Function Recursively System.out.println("String to be passed in Recursive Function: "+myStr.substring(1)); return reverseString(myStr.substring(1)) + myStr.charAt(0); } }
🌐
w3resource
w3resource.com › java-exercises › string › java-string-exercise-44.php
Java - Reverse a string using recursion
March 2, 2026 - System.out.print(str1.charAt(str1.length() - 1)); // Recursive call to reverseString method by excluding the last character. reverseString(str1.substring(0, str1.length() - 1)); } } // Main method to execute the program. public static void main(String[] args) { String str1 = "The quick brown fox jumps"; // Given input string.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › reverse-a-string-using-recursion
Print reverse of a string using recursion - GeeksforGeeks
March 6, 2025 - The idea is to begin with both corners, swap the corner characters and then make recursive call for the remaining string. ... #include <bits/stdc++.h> using namespace std; void reverse(string &str, int start, int end) { if (start >= end) return; ...
🌐
Blogger
javarevisited.blogspot.com › 2012 › 01 › how-to-reverse-string-in-java-using.html
How to Reverse String in Java Using Iteration and Recursion - Example
How to reverse String in Java is a popular core java interview question and asked on all levels from junior to senior java programming jobs. since Java has rich API most java programmer answer this question by using StringBuffer reverse() method which easily reverses a String in Java and its right way if you are programming in Java but the most interview doesn't stop there and they ask the interviewee to reverse String in Java without using StringBuffer or they will ask you to write an iterative reverse function which reverses string in Java. In this tutorial, we will see how to reverse a string in a both iterative and recursive fashion.
🌐
coderolls
coderolls.com › java-reverse-string-using-recursion
How To Reverse A String In Java Using Recursion - Coderolls
December 8, 2021 - * * @author gaurav * */ public class ReverseStringUsingRecursion { public static void main(String[] args) { String str = "hello"; System.out.println(reverse(str)); } public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return reverse(str.substring(1)) + str.charAt(0); } } ... The example java program given in the above tutorial can be found at this GitHub Gist. Please write you thoughts in the comment section below. PREVIOUSFor-each loop in Java or Enhanced For loop in Java
🌐
Java Training School
javatrainingschool.com › home › 2022 › august › reverse a string using recursion
Reverse a String using Recursion - Java Training School
August 25, 2022 - When there is only one letter remaining, simply append the it to the StringBuffer object and break the recursive call. Interesting Fact -> We all know the legendary Bollywood singer Kishor Kumar. There is an interesting fact about him. Often, upon being asked his name, he used to tell his name in reverse order of alphabets. So, let’s see what he used to say by the running the below program that reserses a string. ... package com.javatrainingschool; public class StringReversalUsingRecursion { private static StringBuffer reversedName = new StringBuffer(); public static String reverseStringM(St
🌐
Programiz
programiz.com › java-programming › examples › reverse-sentence
Java Program to Reverse a Sentence Using Recursion
Java Recursion · Java Strings · Java if...else Statement · public class Reverse { public static void main(String[] args) { String sentence = "Go work"; String reversed = reverse(sentence); System.out.println("The reversed sentence is: " + reversed); } public static String reverse(String sentence) { if (sentence.isEmpty()) return sentence; return reverse(sentence.substring(1)) + sentence.charAt(0); } } Output: The reversed sentence is: krow oG · In the above program, we've a recursive function reverse().
🌐
Javatpoint
javatpoint.com › reverse-a-string-using-recursion-in-java
Reverse a String Using Recursion in Java - Javatpoint
Java Program to prove that strings are immutable in java · Java program to reverse a given string with preserving the position of spaces
🌐
Techie Delight
techiedelight.com › home › basic › reverse a string using recursion – c, c++, and java
Reverse a string using recursion – C, C++, and Java | Techie Delight
September 19, 2025 - As seen in the previous post, we can easily reverse a given string using a stack data structure. As the stack is involved, we can easily convert the code to use the call stack. The implementation can be seen below in C and C++: ... The above solution uses a static variable, which is not recommended. We can easily solve this problem without using any static variable. This approach is almost similar to approach #3 discussed here. Following is the implementation in C, C++, and Java based on the above idea:
🌐
CodeGym
codegym.cc › java blog › random › different ways to reverse a string in java
Different Ways to Reverse a String in Java
February 1, 2023 - The third method is using recursion, where we call a recursive function and solve the problem by concatenating the first character of the string with the reversed substring of the remaining characters. The fourth method is by using an array to reverse a string in java.
🌐
Medium
medium.com › @jasonwei_613 › java-reverse-string-recursion-f3dcaa3d90e2
Java Reverse String (Recursion). How do you use Recursion to reverse an… | by Jason Wei | Medium
May 21, 2019 - The base case is the condition that just returns a value without making a call of the function. Usually this defines the bottom of the recursion. For example, in the problem if there’s a null array passed in you can’t do anything with the null array, because no matter how many times you call the helper function you’ll still get a null array.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Reverse A String Using Recursion - Java Code Geeks
June 30, 2020 - 1. Introduction In this article, You're going to learn how to reverse a string using recursion approach. The first program is to reverse a string and the