Java Program to Reverse Words of a Sentence

  • Java program to reverse a sentence.
  • Write 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;

/**
 * Java Program to
 */
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();
        // Split sentence into words using split method of String
        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