ISC Practicals and Theory - Alphabetical Word Sort (OOP)
Updated 21 Oct 2026
This program reads a sentence and prints its words in alphabetical (dictionary) order. It is written as a class with a parameterised constructor and small methods that each do one job: countWords(), extract(), compare(), swap() and sortWords(). The words are taken out with charAt(), substring() and length(), with no split() and no StringTokenizer, and sorted by a hand-written bubble sort.
Definition
A sentence is a line that ends with ., ? or !. Its words are the groups of characters separated by one or more spaces; the terminator is not part of the last word. In ascending alphabetical order apple comes before banana, and fig before pear.
Words are compared with the String method compareToIgnoreCase(), which returns a positive number if the first word comes after the second, 0 if they are equal ignoring case and a negative number if it comes before. compareTo() would put every capital letter before every small letter (Zebra before apple) because capital letters have smaller character codes, so the case-blind version is used and the words print in their original case.
Example: pear Apple fig. gives Apple fig pear. Words equal ignoring case are never swapped, so they stay in the order typed.
Algorithm
mainreads the line withScannerand creates the object with the parameterised constructorWordSort(line), which stores the trimmed line insent.isValid()checks thatsentis not empty and ends with.,?or!; otherwisemainprintsINVALID INPUTand stops.countWords()returns the number of words, whichmainstores inn. It scans the characters before the terminator: a space is skipped, any other character starts a word (add 1 tocount) andimoves to the end of that word.- If
nis less than 1 or more than 50,mainprintsINVALID INPUTand stops. extract()createswwithnplaces and scans the sentence again. For each word it storessent.substring(start, i)inw[k].sortWords()is a bubble sort. Forifrom 0 ton - 2andjfrom 0 ton - 2 - i, ifcompare(w[j], w[j + 1]) > 0it callsswap(j, j + 1).compare(a, b)returnsa.compareToIgnoreCase(b).swap(x, y)interchangesw[x]andw[y]using a temporary variablet.
display()printsSorted words:followed by each word, with a space before it.
Program
The constructor stores the sentence. isValid(), countWords() and extract() prepare the words, compare() and swap() are the two helpers of sortWords(), and display() prints. main reads the input, creates the object and calls the methods.
import java.util.Scanner;
/* Class WordSort stores a sentence, extracts its words without split() or
StringTokenizer and arranges them in alphabetical (dictionary) order
using bubble sort. Every method does one job. */
public class WordSort
{
String sent; // the sentence (trimmed, with its terminator)
String w[]; // array that stores the words of the sentence
int n; // number of words in the sentence
/* Parameterised constructor. Parameter s: the sentence typed by the user.
trim() removes spaces at the two ends of the line. */
WordSort(String s)
{
sent = s.trim();
w = null;
n = 0;
}
/* Returns true if the sentence is not empty and ends with '.', '?' or '!',
otherwise false. */
boolean isValid()
{
if (sent.length() == 0)
return false;
char last = sent.charAt(sent.length() - 1); // the terminator
return last == '.' || last == '?' || last == '!';
}
/* Counts the words of the sentence and returns the count.
The last character (the terminator) is not examined. */
int countWords()
{
int len = sent.length() - 1; // length without the terminator
int i = 0;
int count = 0; // number of words found so far
while (i < len)
{
if (sent.charAt(i) == ' ') // extra space: skip it
i++;
else
{
count++; // a new word starts here
while (i < len && sent.charAt(i) != ' ')
i++; // move to the end of the word
}
}
return count;
}
/* Extracts the words one by one with substring() and stores them in w.
Uses n, the number of words, to make the array. */
void extract()
{
int len = sent.length() - 1; // length without the terminator
int i = 0, k = 0;
w = new String[n];
while (i < len)
{
if (sent.charAt(i) == ' ')
i++;
else
{
int start = i; // index where the word begins
while (i < len && sent.charAt(i) != ' ')
i++;
w[k] = sent.substring(start, i); // word = start to i - 1
k++;
}
}
}
/* Parameters a and b: two words. Returns a negative number if a comes
before b in the dictionary, 0 if they are equal and a positive number
if a comes after b. The case of the letters is ignored. */
int compare(String a, String b)
{
return a.compareToIgnoreCase(b);
}
/* Parameters x and y: positions in w. Interchanges the two words. */
void swap(int x, int y)
{
String t = w[x]; // temporary variable
w[x] = w[y];
w[y] = t;
}
/* Bubble sort: arranges the words in ascending alphabetical order */
void sortWords()
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (compare(w[j], w[j + 1]) > 0) // out of order
swap(j, j + 1);
}
}
}
/* Prints the sorted words on one line, separated by a space */
void display()
{
System.out.print("Sorted words:");
for (int i = 0; i < n; i++)
System.out.print(" " + w[i]);
System.out.println();
}
/* main reads the sentence, creates the object and calls the methods.
The sentence must have at least 1 and at most 50 words, else
INVALID INPUT is printed. */
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String line = sc.nextLine(); // sentence typed by the user
WordSort ob = new WordSort(line); // object of class WordSort
if (!ob.isValid())
{
System.out.println("INVALID INPUT");
return;
}
ob.n = ob.countWords();
if (ob.n < 1 || ob.n > 50)
{
System.out.println("INVALID INPUT");
return;
}
ob.extract();
ob.sortWords();
ob.display();
}
}Variable description table
| Variable | Data Type | Purpose |
|---|---|---|
sent | String | Data member: the sentence, trimmed, with its terminator |
w | String[] | Data member: array that holds the words of the sentence |
n | int | Data member: number of words in the sentence |
s | String | Parameter of the constructor: the line typed by the user |
last | char | Local to isValid(): the last character of the sentence |
len | int | Local to countWords() and extract(): length of the sentence without its terminator |
i | int | Index into the sentence in countWords() and extract(); pass counter in sortWords(); position counter in display() |
count | int | Local to countWords(): number of words found so far, returned at the end |
k | int | Local to extract(): index in w where the next word is stored |
start | int | Local to extract(): index at which the current word begins |
a | String | Parameter of compare(): first word |
b | String | Parameter of compare(): second word |
x | int | Parameter of swap(): position of the first word |
y | int | Parameter of swap(): position of the second word |
t | String | Temporary variable used in swap() |
j | int | Inner loop counter in sortWords(): position of the word being compared |
sc | Scanner | Reads the sentence from the keyboard in main |
line | String | Local to main: the sentence as typed |
args | String[] | Command line arguments of main (not used) |
ob | WordSort | Object created in main to call the methods |
Sample input and output
Sample 1
Enter a sentence: pear Apple fig.
Sorted words: Apple fig pearSample 2
Enter a sentence: Zebra apple Mango apple banana !
Sorted words: apple apple banana Mango ZebraSample 3
Enter a sentence: Hello?
Sorted words: HelloSample 4
Enter a sentence: Welcome to Prashnika
INVALID INPUTSample 5
Enter a sentence: .
INVALID INPUTDry run
Input pear Apple fig. The sentence has 15 characters, so len = 14. Characters 0 to 3 are pear, 4 is a space, 5 to 9 are Apple, 10 is a space, 11 to 13 are fig and 14 is the terminator ..
Counting and extracting. countWords() returns 3, so n = 3. Then extract() runs:
| Step | i | Character at i | Action | start | k | w |
|---|---|---|---|---|---|---|
| 1 | 0 | p | word begins; i moves to 4 | 0 | 0 | w[0] = "pear" |
| 2 | 4 | space | skip | 1 | ||
| 3 | 5 | A | word begins; i moves to 10 | 5 | 1 | w[1] = "Apple" |
| 4 | 10 | space | skip | 2 | ||
| 5 | 11 | f | word begins; i moves to 14 | 11 | 2 | w[2] = "fig" |
Sorting. n = 3, so there are two passes.
Pass i | j | compare(w[j], w[j+1]) | Action | w after |
|---|---|---|---|---|
| 0 | 0 | pear, Apple: positive | swap(0, 1) | [Apple, pear, fig] |
| 0 | 1 | pear, fig: positive | swap(1, 2) | [Apple, fig, pear] |
| 1 | 0 | Apple, fig: negative | no swap | [Apple, fig, pear] |
The program prints Sorted words: Apple fig pear, the same as the real run above.
Variations
- Length order "Arrange the words of a sentence in ascending order of their length."
- Descending order "Sort the words of a sentence in descending alphabetical order."
- Selection sort "Arrange the words of a sentence in alphabetical order using selection sort."