Longest Word in Java: Solution, Explanation & Practice
Find the longest word in a sentence
Problem summary
Write a program that finds the longest word in a sentence.
Starter code
public class Main {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps"; // Test case 1
// Find longest word
// Print: Longest word: <word>
}
}Expected output and test cases
- quick is longest (5 chars)
Longest word: quick
- Longest in sentence
Longest word: programming
- Single word
Longest word: hello
Hints
- Split sentence into words
- Track longest word found
- Compare lengths to find maximum
Validated solution
Reveal Java solution
public class Main {
static String longestWord(String sentence) {
String best = "";
for (String word : sentence.trim().split("\\s+")) {
if (word.length() > best.length()) best = word;
}
return best;
}
public static void main(String[] args) {
System.out.println("Longest word: " + longestWord("the quick brown fox"));
}
}How to approach the problem
Track the longest candidate while visiting each token. Using a strict greater-than comparison means the first word wins when two words tie, which is a useful deterministic rule.
Approach
- Split the sentence into whitespace-separated words.
- Keep one best word.
- Replace it only when a longer word appears.
Time and space complexity
Time: O(n). Space: O(n).
Edge cases to test
- An empty or whitespace-only sentence returns an empty word with this contract.
- Punctuation remains attached unless you normalize it first.
Common mistakes
- Using >= accidentally changes the tie rule to last word.
- Assuming every split result is a meaningful word without trimming.
Follow-up challenge
Return every word tied for the maximum length after stripping punctuation.
Related Strings exercises
- Practice First Non-Repeating Character in Java
- Practice Anagram Check in Java
- Practice Remove All Spaces in Java
Practice all Strings exercises · Run this idea in the Java compiler