Java String Program · S12
Find the Longest Word in a String in Java
Scan the words of a sentence and keep the longest one. The details that matter are extra spaces, blank input and which word wins a tie.
Problem Statement
Write a method that returns the longest word in a string, where words are separated by one or more whitespace characters.
If two words have the same maximum length, return the one that appears first. If the string is empty or contains only spaces, return an empty string.
Input/Output Examples
"Java streams are powerful"Output"powerful"Explanation: powerful has 8 letters, one more than streams."cat dog"Output"cat"Explanation: both words have 3 letters, so the first one wins." "Output""Explanation: there are no words.Visual Explanation
- Word 1wordJavalength 4 4 > 0, new longest
- Word 2wordstreamslength 7 7 > 4, new longest
- Word 3wordarelength 3 3 > 7? no, keep
- Word 4wordpowerfullength 8 8 > 7, new longest
- Doneall words checked"powerful"
"Java streams are powerful": a word replaces the current longest (purple) only when it is strictly longer.Because the comparison is a strict >, a later word of the same length never replaces an earlier one. That single character in the code is what makes the first word win a tie.
Approaches
Both approaches split the text into words. One keeps the longest in a loop; the other asks a stream for its maximum.
Approach 1: split() and a Loop (Recommended)
Idea: split the trimmed string on \\s+, then keep the longest word seen so far.
- Call
strip(); if the result is empty, return"". - Split on
\\s+so that any run of whitespace separates words. - Replace
longestonly when a word is strictly longer, then return it.
Time: O(n) · Space: O(n). The array of words takes extra memory.
Approach 2: Streams and max()
Idea: stream the words and pick the maximum by length with Comparator.comparingInt(String::length).
- Split the stripped string into words.
- Call
max()with a length comparator. - Use
orElse("")as a safety net for an empty stream.
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: split() and a Loop (Recommended)
The strict > keeps the first word on a tie, and the empty check handles blank input before splitting.
public class LongestWordSplit {
// Returns the first longest word; ties keep the earlier word because of the strict >
static String longestWord(String text) {
String trimmed = text.strip();
if (trimmed.isEmpty()) {
return "";
}
String longest = "";
for (String word : trimmed.split("\\s+")) {
if (word.length() > longest.length()) {
longest = word;
}
}
return longest;
}
public static void main(String[] args) {
String[] inputs = {"Java streams are powerful", "cat dog", " "};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> \"" + longestWord(text) + "\"");
}
}
}
"Java streams are powerful" -> "powerful" "cat dog" -> "cat" " " -> ""
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Streams and max()
When two words are equally long, Stream.max() keeps the earlier one, so the tie rule matches the loop version. A blank input produces one empty word, which is returned as "".
import java.util.Arrays;
import java.util.Comparator;
public class LongestWordStream {
// Stream.max() keeps the first element when two words have the same length
static String longestWord(String text) {
return Arrays.stream(text.strip().split("\\s+"))
.max(Comparator.comparingInt(String::length))
.orElse("");
}
public static void main(String[] args) {
String[] inputs = {"Java streams are powerful", "cat dog", " "};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> \"" + longestWord(text) + "\"");
}
}
}
"Java streams are powerful" -> "powerful" "cat dog" -> "cat" " " -> ""
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| split() and a Loop | O(n) | O(n) |
| Streams and max() | O(n) | O(n) |
Here n is the length of the string. Splitting reads every character once and stores the words, so both approaches use O(n) time and space.
Interview Tips and Recommended Approach
- Ask about ties. First word, last word or all of them? Use
>to keep the first and>=to keep the last. - Split on
\\s+, not on a single space. Otherwise, double spaces produce empty strings in the word array. - Clarify punctuation. With whitespace as the only separator,
"fun!"is a four-character word. Strip punctuation first if the interviewer wants letters only. - Test blank and one-word inputs to make sure the method never throws and never returns
null.
Recommended Approach: split() and a Loop
Why: it is easy to follow, handles extra spaces and blank input, and makes the tie rule visible through the strict comparison. It also uses only basic language features.