Find the Second Shortest Word in a Sentence in Java — Definition, Examples and Program

Learn how to find the second shortest word in a sentence in Java using a simple character-by-character approach without using split() or advanced string methods.

Find the Second Shortest Word in a Sentence in Java

Finding the second shortest word in a sentence means identifying the word whose length is greater than the shortest word but smaller than all other words.

This problem improves understanding of string traversal, comparisons, and edge case handling without relying on built-in string utilities.

Understanding the Problem

Given a sentence, we must:

Example 1

Input: Java is very easy to learn

Output: is

Example 2

Input: Find the second shortest word

Output: the

Logic Explanation

  1. Traverse the sentence character by character.
  2. Build each word until a space is found.
  3. Compare word length with shortest and second shortest.
  4. Update values accordingly.
  5. Check the last word after the loop.

Java Program to Find the Second Shortest Word


import java.util.Scanner;

public class SecondShortestWord {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a sentence: ");
        String str = sc.nextLine();

        String word = "";
        String shortest = "";
        String secondShortest = "";

        for (int i = 0; i < str.length(); i++) {

            char ch = str.charAt(i);

            if (ch != ' ') {
                word = word + ch;
            } else {
                if (shortest.equals("") || word.length() < shortest.length()) {
                    secondShortest = shortest;
                    shortest = word;
                } else if (!word.equals(shortest) &&
                           (secondShortest.equals("") || word.length() < secondShortest.length())) {
                    secondShortest = word;
                }
                word = "";
            }
        }

        // Check last word
        if (shortest.equals("") || word.length() < shortest.length()) {
            secondShortest = shortest;
            shortest = word;
        } else if (!word.equals(shortest) &&
                   (secondShortest.equals("") || word.length() < secondShortest.length())) {
            secondShortest = word;
        }

        System.out.println("Second shortest word: " + secondShortest);
    }
}

Sample Output


Enter a sentence: Java is very easy to learn
Second shortest word: is

Important Notes

Practice Challenges

  1. Modify the program to ignore punctuation marks.
  2. Find the third shortest word in a sentence.
  3. Print both shortest and second shortest words together.

This problem strengthens string comparison logic and is frequently asked in Java interviews and coding tests.