Find Longest Word in a String in Java
Problem
The longest word in a sentence is whichever word has the most characters once every word's length has been compared.
Given a sentence, find its longest word.
Java Program
public class FindLongestWord {
public static void main(String[] args) {
String str = "The quick brown fox jumps";
String[] words = str.split(" ");
String longest = words[0];
for (String word : words) {
if (word.length() > longest.length()) { // update whenever a strictly longer word is found
longest = word;
}
}
System.out.println("Longest word: " + longest);
}
}Output
Core Logic
Splitting the sentence into words and keeping track of the longest one seen so far, one pass through the array, finds the winner.
- 1
str.split(" ")breaks the sentence into an array of individual words. - 2
longeststarts out holding the first word,words[0]. - 3A loop visits every word, comparing its length against
longest.length()with>. - 4Whenever a longer word is found,
longestis updated to that word.
"The quick brown fox jumps", 'quick', 'brown', and 'jumps' all tie at 5 letters — longest is updated to 'quick' first and, since later words aren't strictly longer, it stays 'quick'.Key Point: Using > rather than >= means the first word to reach the maximum 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 FindLongestWordStream {
public static void main(String[] args) {
String str = "The quick brown fox jumps";
// Compares every word by length and keeps the longest one
String longest = Arrays.stream(str.split(" "))
.max(Comparator.comparingInt(String::length))
.orElseThrow();
System.out.println("Longest word: " + longest);
}
}
Output
Core Logic
Once the words are split, a stream can find the longest one directly instead of a manual running-maximum 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
.max(...)compares every word using that comparator and keeps the single longest 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 'quick' as the longest, matching the manual version's first-seen tiebreak.Key Point: Comparator.comparingInt() avoids writing a custom Comparator by hand — it builds one directly from a method that extracts an int key from each element.
Why: split() still allocates an array holding every word, and max() then makes one pass over it comparing lengths.