Longest Word
Find the longest word in a sentence.
BeginnerTopic: Module 4: String Programs
Java Longest Word Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine();
String[] words = s.trim().split("\\s+");
String longest = "";
for (String w : words) {
if (w.length() > longest.length()) {
longest = w;
}
}
System.out.println("Longest word: " + longest);
sc.close();
}
}Output
Enter a sentence: Java is powerful language Longest word: powerful
Understanding Longest Word
We split on spaces and track the word with maximum length.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.