Introduction
Finding the longest word in a String is a common Java programming exercise. The goal is to examine the words in a sentence and identify the word that contains the most characters.
For example, consider the sentence "Java developers build reliable applications". The longest word is "applications" because it contains 12 characters. A Java program can find this word by splitting the sentence into individual words and comparing their lengths.
This problem is useful for practicing String manipulation, arrays, loops, and the Java Stream API. Similar techniques are also used in text processing applications that analyze words and their lengths.
In this tutorial, I will demonstrate three ways to find the longest word in a String. You will learn how to use a traditional for loop, Java Streams, and regular expressions. I will also explain how to handle punctuation, empty input, and words with the same maximum length.
1. Understanding the Longest Word Problem
Consider the following String:
Java developers build reliable applications
The sentence contains five words. Their lengths are:
| Word | Length |
|---|---|
| Java | 4 |
| developers | 10 |
| build | 5 |
| reliable | 8 |
| applications | 12 |
The word "applications" has the greatest length.
Therefore, the expected output is:
Longest word: applications
Length: 12
The basic algorithm involves three steps:
- Split the input String into individual words.
- Compare the length of each word with the longest word found so far.
- Return the word with the greatest length.
If multiple words have the same maximum length, the examples in this tutorial return the first one unless stated otherwise.
2. Find the Longest Word in Java Using a For Loop
A traditional for loop is one of the simplest ways to find the longest word in a String.
The program splits the sentence into words and processes them one by one. It keeps track of the longest word found so far and updates the result whenever it encounters a longer word.
This approach is easy to understand and works well for beginner-level Java programs.
Java Program Using a For Loop
public class LongestWordUsingLoop {
public static void main(String[] args) {
String input = "Java developers build reliable applications";
String longestWord = findLongestWord(input);
System.out.println("Longest word: " + longestWord);
System.out.println("Length: " + longestWord.length());
}
/**
* Finds the first longest word in a whitespace-separated String.
*
* @param input the sentence to analyze
* @return the longest word, or an empty String if no word exists
* @throws IllegalArgumentException if input is null
*/
public static String findLongestWord(String input) {
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
if (input.isBlank()) {
return "";
}
// Split the sentence at one or more whitespace characters.
String[] words = input.trim().split("\\s+");
String longestWord = "";
// Update the result only when a longer word is found.
for (String word : words) {
if (word.length() > longestWord.length()) {
longestWord = word;
}
}
return longestWord;
}
}
Output
Longest word: applications
Length: 12
How Does the Program Work?
Step 1: Validate the Input
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
if (input.isBlank()) {
return "";
}
The method checks whether the input is null or contains only whitespace.
A null input is rejected with an IllegalArgumentException.
If the String is empty or contains only whitespace, the method returns an empty String because no word is available.
Step 2: Split the String into Words
String[] words = input.trim().split("\\s+");
The trim() method removes leading and trailing characters within its supported whitespace range.
The split() method divides the String using the regular expression \\s+.
This expression matches one or more whitespace characters, so it can handle multiple consecutive spaces and tabs.
For the given sentence, the resulting array contains:
["Java", "developers", "build", "reliable", "applications"]
Step 3: Compare Word Lengths
String longestWord = "";
for (String word : words) {
if (word.length() > longestWord.length()) {
longestWord = word;
}
}
The variable longestWord initially contains an empty String.
The loop checks each word using the length() method.
When the current word is longer than the stored word, the program updates longestWord.
For the sample input, the result changes as follows:
Javabecomes the longest word with a length of 4.developersreplaces it with a length of 10.buildandreliableare shorter, so the result does not change.applicationsbecomes the longest word with a length of 12.
Step 4: Return the Result
return longestWord;
After processing every word, the method returns the longest word found.
When should you use this approach?
Use the loop-based approach for simple String processing tasks and coding interviews. It is readable, efficient, and does not require the Stream API.
3. Find the Longest Word Using Java Streams
The Java Stream API provides another way to find the longest word in a String.
Instead of writing an explicit loop, you can create a Stream of words and use a reduction operation to keep the longest word.
The following example uses Stream.reduce(). It also preserves the first longest word when multiple words have the same length.
Java Program Using Streams
import java.util.Arrays;
public class LongestWordUsingStreams {
public static void main(String[] args) {
String input = "Java developers build reliable applications";
String longestWord = findLongestWord(input);
System.out.println("Longest word: " + longestWord);
System.out.println("Length: " + longestWord.length());
}
/**
* Finds the first longest word using a sequential Stream.
*/
public static String findLongestWord(String input) {
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
if (input.isBlank()) {
return "";
}
String[] words = input.trim().split("\\s+");
// Keep the earlier word when two words have equal lengths.
return Arrays.stream(words)
.reduce("", (longest, word) ->
word.length() > longest.length()
? word
: longest
);
}
}
Output
Longest word: applications
Length: 12
Explanation
The first important statement is:
Arrays.stream(words)
This creates a sequential Stream containing the words from the array.
The reduce() method then combines the words into a single result:
.reduce("", (longest, word) ->
word.length() > longest.length()
? word
: longest
);
The empty String is the initial result.
For every word, the reduction checks whether the current word is longer than the longest word found so far.
- If the current word is longer, it becomes the new result.
- Otherwise, the existing result is preserved.
Because the comparison uses > rather than >=, a word with an equal length does not replace the earlier word.
For example, if the input is "code test", both words contain four characters. The method returns "code".
When should you use this approach?
This approach is useful when practicing Java Streams or integrating word processing into an existing Stream pipeline.
For a small task such as finding the longest word, the traditional loop may be easier for beginners to read.
4. Find the Longest Word Ignoring Punctuation
Real-world text often contains punctuation marks such as commas, periods, and exclamation marks.
Consider the following sentence:
Java, Spring Boot, and microservices!
If you split this sentence only on spaces, some words will retain their punctuation.
For example, "microservices!" includes an exclamation mark, which increases its String length even though the punctuation is not part of the word.
To handle this, you can use a regular expression that treats punctuation and whitespace as separators.
Java Program Using Regular Expressions
import java.util.regex.Pattern;
public class LongestWordIgnoringPunctuation {
// Separate words using characters that are not letters or digits.
private static final Pattern WORD_SEPARATOR =
Pattern.compile("[^\\p{L}\\p{N}]+");
public static void main(String[] args) {
String input = "Java, Spring Boot, and microservices!";
String longestWord = findLongestWord(input);
System.out.println("Longest word: " + longestWord);
System.out.println("Length: " + longestWord.length());
}
/**
* Finds the first longest word while ignoring punctuation
* and whitespace. This uses a simple Unicode-aware tokenizer.
*/
public static String findLongestWord(String input) {
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
String longestWord = "";
int longestLength = 0;
// Split into words and skip empty values.
for (String word : WORD_SEPARATOR.split(input)) {
if (word.isEmpty()) {
continue;
}
// Count Unicode code points rather than UTF-16 code units.
int currentLength = word.codePointCount(0, word.length());
if (currentLength > longestLength) {
longestWord = word;
longestLength = currentLength;
}
}
return longestWord;
}
}
Output
Longest word: microservices
Length: 13
How Does the Program Work?
The program uses the following regular expression:
[^\\p{L}\\p{N}]+
In this Java String literal:
\p{L}represents Unicode letters.\p{N}represents Unicode numbers.[^...]matches characters outside the specified categories.+matches one or more consecutive separator characters.
This allows the program to separate words from common punctuation marks and whitespace.
The program also uses:
word.codePointCount(0, word.length())
This method counts the Unicode code points in the word instead of counting UTF-16 code units.
It is useful when processing words containing supplementary Unicode characters.
Finally, the program compares the lengths and returns the first word with the greatest number of code points.
Important: This is a simplified word tokenizer. It separates contractions and hyphenated words. It also treats combining marks as separators. Applications that need language-specific word boundaries should use a suitable text-segmentation approach.
5. Find All Longest Words When Multiple Words Have the Same Length
Sometimes a sentence contains more than one word with the maximum length.
For example, consider the following input:
Java code test
All three words contain four characters.
The previous examples return the first longest word, which is "Java".
If you want to return every word tied for the maximum length, you can store the matching words in a List.
Java Program to Find All Longest Words
import java.util.ArrayList;
import java.util.List;
public class FindAllLongestWords {
public static void main(String[] args) {
String input = "Java code test";
List<String> longestWords = findAllLongestWords(input);
System.out.println("Longest words: " + longestWords);
}
/**
* Returns all words tied for the maximum length.
* Repeated occurrences remain in the result.
*/
public static List<String> findAllLongestWords(String input) {
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
List<String> longestWords = new ArrayList<>();
if (input.isBlank()) {
return longestWords;
}
int maxLength = 0;
for (String word : input.trim().split("\\s+")) {
int currentLength = word.length();
if (currentLength > maxLength) {
// A longer word replaces the previous candidates.
longestWords.clear();
longestWords.add(word);
maxLength = currentLength;
} else if (currentLength == maxLength) {
// Keep words tied for the maximum length.
longestWords.add(word);
}
}
return longestWords;
}
}
Output
Longest words: [Java, code, test]
Explanation
The program uses an ArrayList to store the longest words found so far.
When it encounters a word longer than the current maximum, it clears the List and adds the new word.
When it encounters another word with the same maximum length, it adds that word to the List.
This approach is useful when your application needs to display every word tied for the greatest length rather than selecting only the first one.
6. How to Run the Java Programs
You can run these examples in IntelliJ IDEA, Eclipse, VS Code, or from the command line.
Java 17 or later is sufficient. The examples use only the Java standard library, so no external dependencies are required.
Step 1: Create a Java File
Create a file named LongestWordUsingLoop.java.
Copy the complete code from the first example into the file.
Step 2: Compile the Program
Open a terminal in the directory containing the file and run:
javac LongestWordUsingLoop.java
Step 3: Run the Program
java LongestWordUsingLoop
The output should be:
Longest word: applications
Length: 12
To run the remaining examples, save each program in a separate Java file whose filename matches its public class name.
7. Comparing Different Approaches
The approaches covered in this tutorial are suitable for different requirements.
| Approach | Time Complexity | Main Advantage | Best Use Case |
|---|---|---|---|
| For Loop | O(n) | Simple and readable | Beginners and coding interviews |
| Java Streams | O(n) | Declarative reduction | Stream API practice |
| Regular Expressions | Typically O(n) | Handles common punctuation | Basic text processing |
| List of Longest Words | O(n) | Returns all maximum-length words | Handling tied results |
Here, n represents the size of the input text.
All approaches scan the input to identify words and compare their lengths. Their overall processing time is linear under the usual assumptions for these operations.
The methods that use split() also allocate an array and individual word Strings. Their memory usage depends on the number and length of the extracted words.
For most beginner-level problems, the traditional loop is the simplest solution.
8. Common Mistakes When Finding the Longest Word
1. Splitting Only on a Single Space
Using split(" ") can produce empty elements when the input contains consecutive spaces.
For basic whitespace-separated text, use split("\\s+") instead.
2. Counting Punctuation as Part of a Word
When you split only on whitespace, punctuation remains attached to words.
For example, "Java!" has a String length of five, even though the word "Java" contains four letters.
Use a suitable tokenizer when punctuation should be excluded.
3. Ignoring Empty Input
An empty String contains no words.
Check for empty or blank input before processing the text. Returning an empty String or an empty result collection is often appropriate.
4. Not Handling Multiple Longest Words
Two or more words may have the same maximum length.
Decide whether your method should return the first matching word, the last matching word, or every word tied for the maximum length.
The choice affects how you implement the comparison.
5. Assuming String.length() Counts Every Visible Character
The String.length() method returns the number of UTF-16 code units.
Some Unicode characters require two code units. For those characters, the length may differ from the number of Unicode code points.
Use codePointCount() when code-point length is required.
For complete user-perceived characters, including certain emoji and combining-character sequences, additional Unicode text segmentation may be necessary.
6. Ignoring Null Values
Calling String methods on a null reference causes a NullPointerException.
When writing reusable methods, validate the input and define a clear policy for null values.
9. Frequently Asked Questions
How do you find the longest word in a Java String?
Split the String into words and compare their lengths using a loop. Store the longest word found so far and update it whenever a longer word appears.
Can I find the longest word using Java Streams?
Yes. Convert the words into a Stream and use a reduction operation or a suitable comparator to identify the longest word.
Which Java method returns the length of a word?
The String.length() method returns the number of UTF-16 code units in a String. For ordinary English words, this corresponds to the number of characters.
How do I find the longest word without counting punctuation?
Use a regular expression or tokenizer to separate words from punctuation before comparing their lengths.
What happens if two words have the same maximum length?
It depends on the implementation. You can return the first word, the last word, or all words tied for the maximum length.
The loop and Stream examples in this tutorial return the first longest word.
What is the time complexity of finding the longest word?
A loop-based solution generally has O(n) time complexity, where n is the length of the input text. It processes the words once after splitting the sentence.
Can the program find the longest word in an empty String?
No word exists in an empty String. A well-designed method should return an empty result or another clearly defined value.
Conclusion
In this tutorial, you learned how to find the longest word in a Java String using a traditional loop, Java Streams, and regular expressions.
The loop-based approach is a good starting point for beginners. It splits the sentence into words and compares their lengths to find the longest one. The Stream API provides an alternative when you want to practice reduction operations.
You also learned how to handle punctuation and multiple words with the same maximum length. These details are important when moving from simple programming exercises to real-world text processing.
For most basic String problems, I recommend using a straightforward loop because it is easy to read and maintain.
As a next step, try writing a Java program to find the shortest word in a String. You can reuse much of the same logic and change the comparison to select the word with the smallest length.
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment