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

  1. Split sentence into words
  2. Track longest word found
  3. 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

  1. Split the sentence into whitespace-separated words.
  2. Keep one best word.
  3. 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 all Strings exercises · Run this idea in the Java compiler