Java Program to Reverse Words of a Sentence

Here is a java program to reverse words of a sentence. Given a sentence, we have to reverse the sequence of words in given sentences. Words of the given sentence are separated by one or multiple space characters.

For Example,
Input Sentence : I love Java Programming
Output Sentence : Programming Java love I

To split a string to multiple words separated by spaces, we will call split() method.
public String[] split(String regex);

split() method returns an array of Strings, after splitting string based of given regex(delimiters).


Java program to reverse words of a sentence

package com.tcc.java.programs;

import java.util.Scanner;

public class ReverseSentence {
    public static void main(String[] args) {
        String input;
        String[] words;
        int i;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a Sentence");
        input = scanner.nextLine();
        words = input.split(" ");
        
        // Now, Print the sentence in reverse order
        System.out.println("Reversed Sentence");
        for (i = words.length - 1; i >= 0; i--) {
            System.out.print(words[i] + " ");
        }
    }
}
Output
Enter a Sentence
I love Java Programming
Reversed Sentence
Programming Java love I 

Recommended Posts
Java Program to Reverse a String
Java Program to Count Words in a Sentence
Java Program To Reverse Digits of a Number using While Loop
Java Program to Reverse a Number using Recursion
C++ Program to Reverse Digits of a Number
C++ Program to Print Array in Reverse Order
Java Program to Check Two Strings are Anagram or Not
Java Program to Concatenate Two Strings
Java Program to Find Length of a String
Java Program to Find Count of Each Character in a String
Java Program to Check Whether two Strings are Equal or Not
All Java Programs