Shortest Word
Find the shortest word in a sentence.
BeginnerTopic: Module 4: String Programs
Java Shortest 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().trim();
if (s.isEmpty()) {
System.out.println("No words");
return;
}
String[] words = s.split("\\s+");
String shortest = words[0];
for (String w : words) {
if (w.length() < shortest.length()) {
shortest = w;
}
}
System.out.println("Shortest word: " + shortest);
sc.close();
}
}Output
Enter a sentence: Java is fun Shortest word: is
Understanding Shortest Word
We initialize with first word and minimize by 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.