This Java example code demonstrates a simple Java program to reverse a sentence using recursion and print the output to the screen.
Example:
public class Reverse {
public static void main(String[] args) {
String sentence = "Welcome back";
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);
}
}
Program Output:
The reversed sentence is: kcab emocleW