In this tutorial you will learn about the Java Program to Reverse Sentence and its application with practical example.
Java Program to Reverse Sentence
In this tutorial, we will learn to create a Java program that will reverse a String in Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Usage of Conditional statements in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java Programming.
What is reversing a sentence?
A sentence is a collection of words, numbers, and symbols. The sentence can be any string of the English Language. Reversing a sentence means writing the sentence in reverse order, from last to first.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the input sentence from the user. 3. Sending that statement to the for loop for reversal. 4. Passing that reversed sentence to the user. 5. Printing the result sentence. 6. End the program. |
Program Description for Reversing the sentence:-
In this program, We will first take the input sentence for the program in string format. Then we will call the reverse function to reverse the sentence in the program. Storing the reversed sentence in a variable. Printing the reversed Sentence to the user.
With the help of the below, code, we will reverse the sentence.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.*;//Importing the packages in the program. public class Reverse { public static void main(String[] args) { //Declaring the required variables for the program String sent = "Let us work";//Giving the sentence to a variable //Calling the reversed function to reverse the sentence String reversed = reverse(sent); //Printing the reversed sentence to the user. System.out.println("The reversed sentence is: " + reversed); } //User defined function to reverse a sentence. public static String reverse(String sent) { if (sent.isEmpty()) return sent; //Returning the sentence return reverse(sent.substring(1)) + sent.charAt(0); } } |
Output:-
In the above program, we have first initialized the required variable.
- sent = string type variable that will hold the value of the input sentence.
- reversed = it will hold the integer value of a reversed sentence.
A user-defined function to reverse a string.
Calling the reverse function in the program.
Printing the reversed sentence to the user.