Find Shortest Word in a String in Java
Problem
The shortest word in a sentence is whichever word has the fewest characters once every word's length has been compared.
Given a sentence, find its shortest word.
Java Program
public class FindShortestWord {
public static void main(String[] args) {
String str = "The quick brown fox jumps";
String[] words = str.split(" ");
String shortest = words[0];
for (String word : words) {
if (word.length() < shortest.length()) { // update whenever a strictly shorter word is found
shortest = word;
}
}
System.out.println("Shortest word: " + shortest);
}
}Output
Core Logic
Splitting the sentence into words and keeping track of the shortest one seen so far, one pass through the array, is the mirror image of finding the longest word.
- 1
str.split(" ")breaks the sentence into an array of individual words. - 2
shorteststarts out holding the first word,words[0]. - 3A loop visits every word, comparing its length against
shortest.length()with<. - 4Whenever a shorter word is found,
shortestis updated to that word.
"The quick brown fox jumps", 'The' and 'fox' both tie at 3 letters — shortest is set to 'The' first and, since 'fox' isn't strictly shorter, it stays 'The'.Key Point: Using < rather than <= means the first word to reach the minimum length wins any tie, keeping the result deterministic.
Why: split() allocates an array holding every word, and the scan then makes one pass over it comparing lengths.
Key Concepts
Approach 2: Java 8
import java.util.Arrays;
import java.util.Comparator;
public class FindShortestWordStream {
public static void main(String[] args) {
String str = "The quick brown fox jumps";
// Compares every word by length and keeps the shortest one
String shortest = Arrays.stream(str.split(" "))
.min(Comparator.comparingInt(String::length))
.orElseThrow();
System.out.println("Shortest word: " + shortest);
}
}
Output
Core Logic
Once the words are split, a stream can find the shortest one directly instead of a manual running-minimum loop.
- 1
Arrays.stream(str.split(" "))turns the split words into aStream<String>. - 2
Comparator.comparingInt(String::length)builds a comparator that compares two words purely by their length. - 3
.min(...)compares every word using that comparator and keeps the single shortest one, wrapped in anOptional. - 4
.orElseThrow()unwraps the result, since the sentence is known not to be empty here.
"The quick brown fox jumps" by length picks out 'The' as the shortest, matching the manual version's first-seen tiebreak.Key Point: The only difference from finding the longest word is min() instead of max() — the same comparator works for both.
Why: split() still allocates an array holding every word, and min() then makes one pass over it comparing lengths.