Reverse Words in a String in Java
Problem
Reversing the words in a sentence means reordering the words themselves while keeping each word's own letters intact.
Given a sentence, reverse the order of its words.
Java Program
public class ReverseWords {
public static void main(String[] args) {
String str = "Hello World Java";
String[] words = str.split(" ");
StringBuilder result = new StringBuilder();
// Walk the words array backward, appending a space between words
for (int i = words.length - 1; i >= 0; i--) {
result.append(words[i]);
if (i != 0) result.append(" ");
}
System.out.println(result.toString());
}
}Output
Core Logic
Splitting the sentence into words and then walking that array backward rebuilds it in reverse word order.
- 1
str.split(" ")breaks the sentence into an array of individual words. - 2A loop walks the array from the last index down to the first.
- 3Each word is appended to a
StringBuilder, with a space added between words but not after the last one. - 4The final
StringBuilderholds the words in reverse order, unchanged internally.
"Hello World Java", the words array is ["Hello", "World", "Java"]; walking it backward builds "Java World Hello".Key Point: Only the order of the words changes — each word's own letters are appended exactly as they were, unlike reversing the whole string character by character.
Why: split() allocates an array holding every word, and the StringBuilder accumulates a result string proportional to the sentence's length.
Key Concepts
Approach 2: Java 8
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ReverseWordsStream {
public static void main(String[] args) {
String str = "Hello World Java";
String[] words = str.split(" ");
// Maps each index to the word at its mirrored position, then joins them with spaces
String result = IntStream.range(0, words.length)
.mapToObj(i -> words[words.length - 1 - i])
.collect(Collectors.joining(" "));
System.out.println(result);
}
}
Output
Core Logic
The same backward walk can be expressed as a stream — map each index to its mirrored word and join the results back together.
- 1
IntStream.range(0, words.length)generates every valid index into the words array. - 2
.mapToObj(i -> words[words.length - 1 - i])maps each index to the word at its mirrored position from the end. - 3
.collect(Collectors.joining(" "))joins the mapped words back together with single spaces between them.
["Hello", "World", "Java"], index 0 maps to "Java", index 1 maps to "World", and index 2 maps to "Hello" — joining gives "Java World Hello".Key Point: Collectors.joining(" ") handles the space-between-words bookkeeping automatically, avoiding the manual 'skip the space after the last word' check the loop version needs.
Why: The stream maps every index to its mirrored word, and Collectors.joining() builds a result string holding the whole sentence.