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 wordsIs,it,a,big,cat(lengths 2, 2, 1, 3, 3). The longest word isbigand the shortest isa.Wonderful!has one word, which is both the longest and the shortest.
Algorithm
mainreads the sentence withnextLine()intosand creates the objectobwithnew WordLength(s). The parameterised constructor storess.trim()insentand sets the other data members to empty or 0.isValid()returnstruewhensenthas at least 2 characters (a word and a terminator) and ends with.,?or!. OtherwisemainprintsINVALID INPUT.findWords()removes the terminator withsubstring(0, length - 1)and scanstextfromi = 0toi = len:- The character is
charAt(i), or a space wheniequalslen, so the last word is also completed. - A non-space character is added to the word
w. - A space after a non-empty
wcompletes the word:update(w)is called andwis cleared.
- The character is
update(w)compares the word with the best so far:- First word: it becomes both
longestandshortest. - Later words:
longestchanges only ifw.length() > maxLen;shortestchanges only ifw.length() < minLen. Equal length changes nothing.
- First word: it becomes both
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
| Variable | Data Type | Purpose |
|---|---|---|
sent | String | Data member: the sentence entered by the user |
longest | String | Data member: the longest word found so far |
shortest | String | Data member: the shortest word found so far |
maxLen | int | Data member: length of the longest word |
minLen | int | Data member: length of the shortest word |
s | String | Parameter of the constructor, and the variable in main that holds the typed sentence |
n | int | Length of the sentence in isValid() |
last | char | Last character of the sentence, tested for ., ? or ! |
w | String | Parameter of update(): a complete word; also the word being formed in findWords() |
text | String | The sentence with its terminator removed |
len | int | Length of text |
i | int | Loop counter: position in text |
ch | char | Character at position i (a space when i equals len) |
sc | Scanner | Reads the line from the keyboard in main |
args | String[] | Command line arguments of main (not used) |
ob | WordLength | Object 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 INPUTSample 5
Enter a sentence: .
INVALID INPUTSample 6
Enter a sentence: Wonderful!
Longest word = Wonderful (length 9)
Shortest word = Wonderful (length 9)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.
i | Word passed to update() | longest | shortest | maxLen | minLen |
|---|---|---|---|---|---|
| 2 | Is (first word) | Is | Is | 2 | 2 |
| 7 | it, 2 is not > 2 and not < 2 | Is | Is | 2 | 2 |
| 9 | a, 1 < 2 so shortest changes | Is | a | 2 | 1 |
| 15 | big, 3 > 2 so longest changes | big | a | 3 | 1 |
| 21 | cat, 3 is not > 3 and not < 1 | big | a | 3 | 1 |
The program prints Longest word = big (length 3) and Shortest word = a (length 1), the same as the real run above.
Variations
- 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."
- Count words "Write a program to count the number of words in a sentence."
- Reverse each word "Write a program to reverse every word of a sentence, keeping the word order."