Longest Word in Java

Find the longest word in a sentence.

BeginnerModule 4: String ProgramsExample 11 of 25
longest-word.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a sentence: ");
7 String s = sc.nextLine();
8
9 String[] words = s.trim().split("\\s+");
10 String longest = "";
11 for (String w : words) {
12 if (w.length() > longest.length()) {
13 longest = w;
14 }
15 }
16 System.out.println("Longest word: " + longest);
17 sc.close();
18 }
19}

Output

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

What's going on

We split on spaces and track the word with maximum length.