Java Program to Find the Longest Word in a String

Ramesh Fadatare
2 min readDec 13, 2024

--

Introduction

Finding the longest word in a string is a useful task in text processing. This task helps you practice string manipulation, splitting strings into words, and comparing lengths of words. This guide will walk you through writing a Java program that identifies the longest word in a given string.

Problem Statement

Create a Java program that:

  • Prompts the user to enter a string.
  • Splits the string into words.
  • Identifies and displays the longest word in the string.

Example:

  • Input: "Java programming language is powerful"
  • Output: "Longest word: programming"

Solution Steps

  1. Read the String: Use the Scanner class to take the string as input from the user.
  2. Split the String into Words: Use the split() method to break the string into words.
  3. Identify the Longest Word: Use a loop to compare the lengths of the words and find the longest one.
  4. Display the Longest Word: Print the longest word in the string.
  5. Close Resources: Close the Scanner class object automatically using the try-resource statement.

Java Program

// Java Program to Find the Longest Word in a String

import java.util.Scanner;

public class LongestWordFinder {
public static void main(String[] args) {
// Step 1: Read the string from the user
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter a string: ");
String input = scanner.nextLine();

// Step 2: Split the string into words
String[] words = input.split("\\s+");

// Step 3: Identify the longest word
String longestWord = "";
for (String word : words) {
if (word.length() > longestWord.length()) {
longestWord = word;
}
}

// Step 4: Display the longest word
System.out.println("Longest word: " + longestWord);
}
}
}

Explanation

Step 1: Read the String

  • The Scanner class is used to read a string input from the user. The nextLine() method captures the entire line as a string.

Step 2: Split the String into Words

  • The split() method is used to divide the string into words based on whitespace. The regex \\s+ handles multiple spaces between words.

Step 3: Identify the Longest Word

  • A for loop iterates through each word in the array.
  • The if statement checks whether the current word is longer than the previously found longest word. If it is, the longestWord variable is updated.

Step 4: Display the Longest Word

  • The program prints the longest word found in the string using System.out.println().

Output

Enter a string: Java programming language is powerful
Longest word: programming

Conclusion

This Java program demonstrates how to find and display the longest word in a user-input string. It covers essential concepts such as string manipulation, using loops for comparison, and handling arrays, making it a valuable exercise for beginners learning Java programming.

--

--

No responses yet