How to Find the Longest Word in a Sentence in Java

Quick Answer (Featured Snippet Ready)

To find the longest word in a sentence in Java, split the sentence into words using split(" "), then compare each word’s length and store the longest one.


Introduction

When working with strings in Java, one common problem developers face is identifying the longest word in a sentence. This is a frequently asked question in coding interviews and beginner Java programs.

In this guide, you’ll learn:

  • Step-by-step logic
  • Java code examples
  • Optimized approaches
  • Real-world use cases

Step-by-Step Logic

To solve this problem, follow these steps:

  1. Take input as a string
  2. Split the sentence into words
  3. Store words in an array
  4. Compare each word’s length
  5. Return the longest word

Java Program to Find Longest Word

public class LongestWord {
public static void main(String[] args) {
String sentence = "Java is a powerful programming language";

String[] words = sentence.split(" ");
String longestWord = "";

for (String word : words) {
if (word.length() > longestWord.length()) {
longestWord = word;
}
}

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

Output

Longest word: programming

How This Code Works

  • split(" ") breaks the sentence into words
  • Loop checks each word’s length
  • Stores the longest word in a variable
  • Updates whenever a longer word is found

This approach runs in O(n) time complexity, making it efficient for large strings.


Alternative Approach (Java 8 Streams)

import java.util.Arrays;
import java.util.Comparator;

public class Main {
public static void main(String[] args) {
String sentence = "Java is simple and powerful";

String longest = Arrays.stream(sentence.split(" "))
.max(Comparator.comparingInt(String::length))
.orElse(null);

System.out.println(longest);
}
}

FAQ’s

What is the easiest way to find the longest word in Java?

Split the string into words and compare their lengths using a loop.

Can there be multiple longest words?

Yes, if multiple words have the same maximum length.

What is the time complexity?

The time complexity is O(n), where n is the number of words.

Can we solve this using streams?

Yes, Java 8 Streams provide a shorter and cleaner solution.

Conclusion

Finding the longest word in a sentence in Java is a simple yet powerful problem that helps you understand string manipulation, loops, and logic building.

By mastering this concept, you’ll be better prepared for:

  • Coding interviews
  • Java programming basics
  • Real-world text processing

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top