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" 
🌐
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); } }
🌐
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().
🌐
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 ...
🌐
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
String str = "India is Great becuase Great is India"; public String reverseWords(String str) { String arr[]=str.split(" "); StringBuilder stb=new StringBuilder(); for(int i=arr.length-1;i>=0;i--) stb.append(arr[i]+" "); return stb.toString(); } Chandraprakash Sarathe --------------------------- http://javaved.blogspot.com/ ... Javin @ spring interview questions answers said... @Chandraprakash, indeed reversing words on String is also good interview question and can be asked in conjunction with reversing string using recursion.
🌐
TutorialsPoint
tutorialspoint.com › Java-program-to-reverse-a-string-using-recursion
Java program to reverse a string using recursion
June 5, 2025 - After each recursive call, concatenate the first character of str.charAt() to the result returned by the recursive function. In the main method, initialize an object of StringReverse and call reverseString with a sample string. Print the result to display the reversed string on the console. Below is the Java program to reverse a string using recursion -
🌐
Vultr Docs
docs.vultr.com › java › examples › reverse-a-sentence-using-recursion
Java Program to Reverse a Sentence Using Recursion | Vultr Docs
December 2, 2024 - Define the method reverseSentence that takes the sentence to be reversed. Use .indexOf(' ') to find the first space (word boundary). Recursively handle the rest of the sentence, moving the first word found to the end until no spaces are left.
Find elsewhere
Top answer
1 of 3
1

This is recursion. Here are documentation for subString() and charAt(). Coming to how this works:

public static String reverse(String word) {

    if ((word == null) || (word.length() <= 1)) {
        return word;
    }
    return reverse(word.substring(1)) + word.charAt(0);
}

Pass1: reverse("user") : return reverse("ser")+'u';

Pass2: reverse("ser")+'u' : return reverse("er")+'s'+'u';

Pass3: reverse("er")+'s'+'u' : return reverse("r")+'e'+'s'+'u';

Pass4: reverse("r")+'e'+'s'+'u' : return 'r'+'e'+'s'+'u'; // because here "r".length()==1

2 of 3
1

The way the recursive part of this works is that to reverse a string, you remove the first character, reverse what's left, and then append the first character to the result. That's what the prof's code is doing.

  • word.substring(1) returns the substring starting at index 1 and going to the end
  • word.charAt(0) returns the character at index 0

There's a bit more going on when the two pieces are appended using +. The issue is that word.charAt(0) has a return type of char. Since the left-hand part of the + is a String, the Java language rules say that the right-hand side must be converted to a String if it isn't one. So the char value is first converted to a Character and then the toString() method of the Character class is called. This returns a String consisting of the single character.

It might have been more efficient code to write that line like:

return reverse(word.substring(1)) + word.substring(0, 1);

The two-argument version of substring returns the substring between the two indexes. That would eliminate the autoboxing and conversion to String.

🌐
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); } }
Top answer
1 of 4
2

Recursive method, using same logic as linked "duplicate", without use of split():

private static String reverseWords(String text) {
    int idx = text.indexOf(' ');
    return (idx == -1 ? text : reverseWords(text.substring(idx + 1)) + ' ' + text.substring(0, idx));
}

The logic is:

  1. Take first char/word
  2. If that is last char/word, return with it
  3. Perform recursive call with remaining text (excluding word-separating space).
  4. Append space (if doing word)
  5. Append first char/word from step 1
  6. Return result

As you can see, when applied to reversing text (characters) instead of words, it's very similar:

private static String reverseText(String text) {
    return (text.length() <= 1 ? text : reverseText(text.substring(1)) + text.charAt(0));
}

For people who like things spelled out, and dislike the ternary operator, here are the long versions, with extra braces and support for null values:

private static String reverseWords(String text) {
    if (text == null) {
        return null;
    }
    int idx = text.indexOf(' ');
    if (idx == -1) {
        return text;
    }
    return reverseWords(text.substring(idx + 1)) + ' ' + text.substring(0, idx);
}
private static String reverseText(String text) {
    if (text == null || text.length() <= 1) {
        return text;
    }
    return reverseText(text.substring(1)) + text.charAt(0);
}

Notice how the long version of reverseText() is exactly like the version in the linked duplicate.

2 of 4
1

Recursive methods could seem a bit hard when beginning but try to do the following :

  • Simplify the problem as much as possible to find yourself with the less complicated case to solve. (Here for example, you could use a sentence with two words).

  • Begin with doing it on a paper, use Pseudocode to help you dealing with the problem with the simplest language possible.

  • Begin to code and do not forget an escape to your recursion.


Solution

public static void main(String[] args) {
    String s = reverseSentence("This sentence will be reversed - I swear".split(" "));
    System.out.println(s);
}

public static String reverseSentence(String[] sentence){
    if (sentence.length <= 1){
        return sentence[0];
    }
    String[] newArray = new String[sentence.length-1];
    for (int i = 0 ; i < newArray.length ; i++){
        newArray[i] = sentence[i];
    }
    return sentence[sentence.length-1] + " " + reverseSentence(newArray);
}
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-reverse-a-sentence-using-recursion
Java Program to Reverse a Sentence Using Recursion
February 22, 2022 - Step 6 - The recursive function is called and the value ‘my_input’ is passed to it. Store the return value Step 7 - Display the result Step 8 - Stop · Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool . import java.util.Scanner; public class Reverse { public static void main(String[] args) { String my_input, my_result; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.print("Enter the sentence : "); my_input = my_scanner.nextLine(); my_result = reverseString(my_input); System.out.println("The reversed input is: " + my_result); } public static String reverseString(String my_input) { if (my_input.isEmpty()) return my_input; return reverseString(my_input.substring(1)) + my_input.charAt(0); } }
🌐
Javacodemonk
javacodemonk.com › reverse-position-of-words-in-a-string-using-recursion-21f43769
Reverse position of words in a string using recursion
November 20, 2020 - Reverse position of words in a string using Recusion Java · public class ReverseWordsInString { public String reverse(String input) { if (input.isEmpty()) { (1) return input; } String[] arr = input.split(" ", 2); (2) String firstWord = arr[0]; String remainingSentence; if (arr.length == 2) remainingSentence = arr[1]; else remainingSentence = ""; return reverse(remainingSentence) + firstWord + " "; (3) } }
🌐
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 › recursive › java-recursive-exercise-6.php
Java Recursive Method: Reverse a given string
public class StringReverser { public ... == 1) { return str; } // Recursive case: reverse the substring starting from the second character and concatenate the first character return reverseString(str.substring(1)) + str.charAt(0); ...
🌐
Scaler
scaler.com › home › topics › reverse a sentence in java
Reverse a Sentence in Java - Scaler Topics
July 5, 2024 - Reverse a sentence means to reverse the words of a sentence in the opposite order. We have used recursion to reverse the sentence in Java by finding the index of the first whitespace and breaking our sentence based on this index.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Reverse A String Using Recursion - Java Code Geeks
June 30, 2020 - 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 second program will read the input from the user. In the previous articles, I have shown already how to reverse a string without using any built-in function and also how to reverse the words in a string.