Java Program to Reverse a Sentence Using Recursion

In this Java program, you’ll learn how to Reverse a Sentence Using Recursion using the Java programming language. 

How to Reverse a Sentence Using Recursion? 

Example 1: Using Recursion 

RUN CODE SNIPPET
public class Main 
{ 
  public static void main(String[] args)  
  { 
    String sentence = "HELLO EVERYONE"; 
    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: ENOYREVE OLLEH

In the above program we have used recursion function. We add the result of next reverse function to the first character of the sentence using charAt(), at each iteration. 

In the end the reverse() returns the reversed sentence. 

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022