Reverse Words in Sentence

Reverse the order of words in a sentence.

BeginnerTopic: Module 4: String Programs
Back

Java Reverse Words in Sentence Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String s = sc.nextLine().trim();

        String[] words = s.split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            sb.append(words[i]).append(" ");
        }
        System.out.println("Reversed words: " + sb.toString().trim());
        sc.close();
    }
}
Output
Enter a sentence: Java is fun
Reversed words: fun is Java

Understanding Reverse Words in Sentence

We split into words and rebuild string from last word to first.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents