How do you reverse the order of words in a sentence in Java?

Split the sentence into words on one or more spaces, reverse the list of words, and join them back with single spaces. Trimming first and splitting on "\\s+" handles extra spaces at the ends and between words.

Key Points: • trim() (or strip()) removes leading and trailing spaces, so split doesn't produce an empty first word. • split("\\s+") treats any run of whitespace as one separator. • Collections.reverse() on a List, or a loop from the end of the array, reverses the order. • String.join(" ", words) puts the sentence back together. • A related question reverses each word but keeps word order: "Java is fun" becomes "avaJ si nuf". Use StringBuilder.reverse() on each word.

Code Example:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ReverseWords {

    static String reverseWords(String s) {
        List<String> words = Arrays.asList(s.trim().split("\\s+"));
        Collections.reverse(words);
        return String.join(" ", words);
    }

    static String reverseEachWord(String s) {
        return Arrays.stream(s.trim().split("\\s+"))
                     .map(w -> new StringBuilder(w).reverse().toString())
                     .collect(Collectors.joining(" "));
    }

    public static void main(String[] args) {
        String sentence = "  Java   interview   preparation is   fun ";
        System.out.println("[" + reverseWords(sentence) + "]");
        System.out.println("[" + reverseEachWord("Java is fun") + "]");
    }
}

Output:

[fun is preparation interview Java] [avaJ si nuf]

Good to Know: Arrays.asList() returns a fixed-size list backed by the array, but Collections.reverse() only swaps elements, so it works. If the interviewer asks for O(1) extra space, work on a char[]: reverse the whole array, then reverse each word inside it.

Interview Tip: A concise interview answer is:

"I trim the sentence, split it on one or more whitespace characters, reverse the resulting list and join it back with single spaces, which also normalises extra spacing. If they want each word reversed instead, I map every word through StringBuilder.reverse and join them in the original order."

Previous question: How do you check whether two strings are anagrams in Java?

Next question: How do you check whether one string is a rotation of another?

More Java Strings interview questions

All Java Strings questions