English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use recursion in Java to reverse the given sentence.
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); } }
When running the program, the output is:
The reversed sentence is: krow oG
In the above program, we have a recursive function reverse().
In each iteration, we use charAt(0) to add (concatenate) the result of the next reverse() function to the first character of the sentence.
Recursive calls must be made before charAt(), because in this way the last character will start to be added to the left. If you reverse the order, you will get the original sentence.
Finally, we end with an empty sentence, and reverse() returns the reversed sentence.
Iteration | reverse() | substring() | reversedString |
---|---|---|---|
1 | reverse("Go work") | "o Work" | result + "G" |
2 | reverse("o Work") | " Work" | result + "o" + "G" |
3 | reverse(" Work") | "Work" | result + " " + "o" + "G" |
4 | reverse("Work") | "ork" | result + "W" + " " + "o" + "G" |
5 | reverse("ork") | "rk" | result + "o" + "W" + " " + "o" + "G" |
6 | reverse("rk") | "k" | result + "r" + "o" + "W" + " " + "o" + "G" |
7 | reverse("k") | "" | result + "k" + "r" + "o" + "W" + " " + "o" + "G" |
Final | reverse("") | - | "" + "k" + "r" + "o" + "W" + " " + "o" + "G" = "kroW oG" |