Longest Word

Find the longest word in a sentence.

JavaBeginner
Java
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

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