Interview Q&A / Java

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

Write a Java method that reverses the order of words in a sentence.

SHORT ANSWER

Trim the text, split on one or more spaces, then join the pieces from last to first with a single space. It takes O(n) time and O(n) space for the word array and result.

Explain it simply

" hello world from Java " should become "Java from world hello": extra spaces disappear and the word order flips.

Line by line

java
public static String reverseWords(String s) {
    String[] words = s.trim().split("\\s+");      // split on runs of spaces
    StringBuilder sb = new StringBuilder();
    for (int i = words.length - 1; i >= 0; i--) {
        sb.append(words[i]);
        if (i > 0) sb.append(' ');                // no trailing space
    }
    return sb.toString();
}
// reverseWords("  hello   world from Java ")  returns "Java from world hello"

trim() removes outer spaces, and the regex \\s+ treats any run of whitespace as a single separator. The loop walks the array backwards and adds a space between words only.

Complexity

Time O(n), space O(n).

What to say in the interview

"I split on whitespace, iterate from the end, and use a StringBuilder to avoid repeated concatenation. For an empty or all-space input, split gives one empty string, so I would add a check if the question requires returning an empty result. If asked to do it in place, I would work on a char array: reverse the whole array, then reverse each word."

Common mistakes

  • Splitting on a single space, which leaves empty strings when words are separated by several spaces.

#java#strings#arrays

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.