Reverse a Sentence in Java

Exercise:

Write a Java Program to reverse a sentence using recursion.

Click Here to View the Solution!
public class ReverseSentence {
  
   public static void main(String[] args) {
     String sentence = "Hello World";
     String reverse = reverse(sentence);
     System.out.println("The reversed sentence is: " + reverse);
   }
  
   public static String reverse(String sentence) {
     if (sentence.isEmpty())
       return sentence;
  
     return reverse(sentence.substring(1)) + sentence.charAt(0);
   } 
 }
Click Here to View the Output!
The reversed sentence is: dlroW olleH
Click Here to View the Explanation!
  • This program turns a sentence into its reverse order by employing method of recursion; in this case named reverse().
  • The input string “Hello World” is being stored in variable ‘sentence’ passed as an argument to reverse().
  • The first step of execution of this function involve checking whether is string is empty or not, if so is the case then the empty string is returned.
  • In the next step, the function ‘substring(1)’ chops off the first character of the input string with each iteration. (” ello Wold”)
  • The upcoming resultant value of the reverse() function is added to the string ‘sentence’, with each pass at 0th index by employing charAt(). (result + “H”)
  • One thing should be taken into consideration here, is that the recurrence is supposed to execute before concatenation, in order to avoid getting the original string as the characters at last index would appear on the left side of the string.
  • In a nutshell, on one hand substring() chops off characters one by one while charAt() will add characters (at 0th index) to the right all while keeping the original string unaltered.
  • Finally the reversed sentence will be displayed on screen.

%d bloggers like this: