Prashnikaप्रश्निका
Code
About
‹ All Computer Science notes

ISC Practicals and Theory - Longest and Shortest Word (OOP)

Updated 21 Oct 2026

This program reads a sentence and prints its longest and shortest word with their lengths, without split() or StringTokenizer. This version is written as a class with a parameterised constructor and small methods that each do one job: one checks the sentence, one scans it, one compares a word with the best so far.

Definition

A word is a run of characters between spaces. The sentence must end with ., ? or !; that last character is removed before the words are formed. Extra spaces are skipped, and spaces at the two ends of the line are ignored. When two words have the same length, the first one is kept.

  • Is it a big cat ? has the words Is, it, a, big, cat (lengths 2, 2, 1, 3, 3). The longest word is big and the shortest is a.
  • Wonderful! has one word, which is both the longest and the shortest.

Algorithm

  1. main reads the sentence with nextLine() into s and creates the object ob with new WordLength(s). The parameterised constructor stores s.trim() in sent and sets the other data members to empty or 0.
  2. isValid() returns true when sent has at least 2 characters (a word and a terminator) and ends with ., ? or !. Otherwise main prints INVALID INPUT.
  3. findWords() removes the terminator with substring(0, length - 1) and scans text from i = 0 to i = len:
    • The character is charAt(i), or a space when i equals len, so the last word is also completed.
    • A non-space character is added to the word w.
    • A space after a non-empty w completes the word: update(w) is called and w is cleared.
  4. update(w) compares the word with the best so far:
    • First word: it becomes both longest and shortest.
    • Later words: longest changes only if w.length() > maxLen; shortest changes only if w.length() < minLen. Equal length changes nothing.
  5. display() prints both words with their lengths.

Program

isValid() checks the sentence, findWords() forms the words, update() compares one word with the longest and shortest so far, display() prints, and main creates the object and calls them.

import java.util.Scanner;

/* Class WordLength reads a sentence and finds its longest and shortest word
   without using split() or StringTokenizer. Ties go to the first word. */
public class WordLength
{
    String sent;       // stores the sentence entered by the user
    String longest;    // stores the longest word found so far
    String shortest;   // stores the shortest word found so far
    int maxLen;        // stores the length of the longest word
    int minLen;        // stores the length of the shortest word

    /* Parameterised constructor. Parameter s: the sentence typed by the user.
       Stores it in sent without the spaces at its two ends and clears the
       other data members. */
    WordLength(String s)
    {
        sent = s.trim();                 // trim() removes the spaces at the two ends
        longest = "";
        shortest = "";
        maxLen = 0;
        minLen = 0;
    }

    /* Returns true if the sentence has at least one character before its last
       character and that last character is '.', '?' or '!', otherwise false. */
    boolean isValid()
    {
        int n = sent.length();
        if (n < 2)                           // empty, or only a terminator
            return false;
        char last = sent.charAt(n - 1);      // last character of the sentence
        return last == '.' || last == '?' || last == '!';
    }

    /* Parameter w: a complete word. Compares it with the longest and shortest
       words so far and replaces them if w is strictly longer or strictly shorter. */
    void update(String w)
    {
        if (longest.length() == 0)           // first word: it is both longest and shortest
        {
            longest = w;
            shortest = w;
            maxLen = w.length();
            minLen = w.length();
        }
        else
        {
            if (w.length() > maxLen)         // strictly longer: ties keep the first word
            {
                longest = w;
                maxLen = w.length();
            }
            if (w.length() < minLen)         // strictly shorter: ties keep the first word
            {
                shortest = w;
                minLen = w.length();
            }
        }
    }

    /* Scans the sentence (without its last character) one character at a time,
       forms each word and passes it to update(). */
    void findWords()
    {
        String text = sent.substring(0, sent.length() - 1);  // terminator removed
        String w = "";                       // word being formed
        int len = text.length();
        for (int i = 0; i <= len; i++)       // i == len acts as a space after the last word
        {
            char ch = ' ';
            if (i < len)
                ch = text.charAt(i);
            if (ch != ' ')
                w = w + ch;                  // letter: add it to the current word
            else if (w.length() > 0)         // space after a word: the word is complete
            {
                update(w);
                w = "";                      // start the next word
            }
        }
    }

    /* Prints the longest and shortest words with their lengths */
    void display()
    {
        System.out.println("Longest word = " + longest + " (length " + maxLen + ")");
        System.out.println("Shortest word = " + shortest + " (length " + minLen + ")");
    }

    /* main reads the sentence, creates the object and calls the methods */
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String s = sc.nextLine();            // sentence typed by the user
        WordLength ob = new WordLength(s);   // object of class WordLength
        if (ob.isValid())
        {
            ob.findWords();
            ob.display();
        }
        else
            System.out.println("INVALID INPUT");
    }
}

Variable description table

VariableData TypePurpose
sentStringData member: the sentence entered by the user
longestStringData member: the longest word found so far
shortestStringData member: the shortest word found so far
maxLenintData member: length of the longest word
minLenintData member: length of the shortest word
sStringParameter of the constructor, and the variable in main that holds the typed sentence
nintLength of the sentence in isValid()
lastcharLast character of the sentence, tested for ., ? or !
wStringParameter of update(): a complete word; also the word being formed in findWords()
textStringThe sentence with its terminator removed
lenintLength of text
iintLoop counter: position in text
chcharCharacter at position i (a space when i equals len)
scScannerReads the line from the keyboard in main
argsString[]Command line arguments of main (not used)
obWordLengthObject created in main to call the methods

Sample input and output

Sample 1

Enter a sentence: The quick brown fox jumps.
Longest word = quick (length 5)
Shortest word = The (length 3)

Sample 2

Enter a sentence:   Is   it a   big   cat ?
Longest word = big (length 3)
Shortest word = a (length 1)

Sample 3

Enter a sentence: Wonderful!
Longest word = Wonderful (length 9)
Shortest word = Wonderful (length 9)

Sample 4

Enter a sentence: Hello world
INVALID INPUT

Sample 5

Enter a sentence: .
INVALID INPUT

Sample 6

Enter a sentence: Wonderful!   
Longest word = Wonderful (length 9)
Shortest word = Wonderful (length 9)

One value per line

Dry run

Input Is it a big cat ? (two spaces at the start). The constructor trims them, so sent is Is it a big cat ?. The terminator is removed, so text is Is it a big cat (length 22, with one space at the end). Spaces while w is empty do nothing; the table shows each call to update(). Here i is the position of the space that completes the word.

iWord passed to update()longestshortestmaxLenminLen
2Is (first word)IsIs22
7it, 2 is not > 2 and not < 2IsIs22
9a, 1 < 2 so shortest changesIsa21
15big, 3 > 2 so longest changesbiga31
21cat, 3 is not > 3 and not < 1biga31

The program prints Longest word = big (length 3) and Shortest word = a (length 1), the same as the real run above.

Variations

  1. Last word on a tie "Write a program to find the longest and shortest word of a sentence; if two words have the same length, display the last one."
  2. Count words "Write a program to count the number of words in a sentence."
  3. Reverse each word "Write a program to reverse every word of a sentence, keeping the word order."