Find the Longest Word in a Sentence in Java — Definition, Examples and Program

Learn how to find the longest word in a sentence in Java using a simple character-by-character approach without relying on split() or advanced string methods.

Find the Longest Word in a Sentence in Java

Finding the longest word in a sentence means identifying the word that contains the maximum number of characters.

This is a very common string problem in interviews and helps build a strong understanding of loops and string traversal.

Understanding the Problem

Given a sentence, we need to:

Example 1

Input: Java programming is powerful

Output: programming

Example 2

Input: Find the longest word

Output: longest

Logic Explanation

  1. Traverse the sentence character by character.
  2. Store characters of the current word.
  3. When a space is encountered, compare word length.
  4. Update the longest word if required.
  5. Check the last word after the loop ends.

Java Program to Find the Longest Word


import java.util.Scanner;

public class LongestWordInSentence {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a sentence: ");
        String str = sc.nextLine();

        String word = "";
        String longestWord = "";

        for (int i = 0; i < str.length(); i++) {

            char ch = str.charAt(i);

            if (ch != ' ') {
                word = word + ch;
            } else {
                if (word.length() > longestWord.length()) {
                    longestWord = word;
                }
                word = "";
            }
        }

        // Check last word
        if (word.length() > longestWord.length()) {
            longestWord = word;
        }

        System.out.println("Longest word: " + longestWord);
    }
}

Sample Output


Enter a sentence: Java programming is powerful
Longest word: programming

Important Notes

Practice Challenges

  1. Modify the program to find all longest words.
  2. Ignore punctuation marks while finding the longest word.
  3. Also print the length of the longest word.

This problem is excellent for mastering string traversal and conditional logic in Java.