Longest Word in Java: 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

Related Strings exercises

Practice all Strings exercises · Run this idea in the Java compiler