To sort words of a sentence alphabetically in Java, tokenize the input string into individual words using StringTokenizer or space-index slicing, store them in a String array, and sort them lexicographically with Bubble Sort or Selection Sort. Comparing adjacent words through compareToIgnoreCase() avoids uppercase-before-lowercase ASCII surprises where 'Z' precedes 'a'. Finally, print each reordered token separated by spaces along with a complete Variable Description Table for ICSE Section B.
- 1. Tokenizing the Sentence Safely Without Trailing Space Bugs
- 2. Lexicographical Swapping Using compareToIgnoreCase() and Bubble Sort
- 3. Dry-Run Trace and ICSE Section B Presentation Rules
- 4. SortSentenceWords.java (BlueJ / ICSE Section B)
- 5. CISCE Variable Description Table (VDT) & Dry Run
- 6. Common Mistakes & Top Scorer Tips
- 7. Interactive Concept Check Quiz
- 8. Frequently Asked Questions
1. Tokenizing the Sentence Safely Without Trailing Space Bugs
Before sorting can happen, a multi-word sentence entered via Scanner.nextLine() must be broken cleanly into standalone words. Many ICSE students manually scan for spaces using charAt(), which often drops the final word unless an artificial space is appended at the end. Using StringTokenizer from java.util handles multiple consecutive spaces, leading blanks, and trailing whitespace automatically without extra guard conditions. First count tokens with countTokens() to size the String array accurately, then populate the array inside a while(st.hasMoreTokens()) loop. If the board question forbids StringTokenizer, normalize the sentence with trim() plus one trailing space and extract substrings between space positions.
- Call sc.nextLine() rather than sc.next() so spaces inside the sentence are captured.
- Trim punctuation or clarify whether commas and periods count as part of a word token.
- Allocate String words[] = new String[n] using st.countTokens() before extracting.
2. Lexicographical Swapping Using compareToIgnoreCase() and Bubble Sort
Sorting strings in Java cannot use relational operators like > or < because array elements hold object references rather than primitive numbers. Instead, Bubble Sort pairs nested loops with words[j].compareToIgnoreCase(words[j + 1]) > 0 to test alphabetical order. That method returns a positive integer whenever the left word comes after the right word in dictionary sequence, ignoring letter case differences. When positive, swap the two String references using a temporary String variable. Using compareTo() directly is valid only when all input letters share the same case; mixed-case sentences like 'BlueJ makes java fun' would otherwise push 'BlueJ' ahead of 'apple' because ASCII 66 is smaller than ASCII 97.
- compareToIgnoreCase() returns 0 for equal words, < 0 when sorted, and > 0 when a swap is required.
- Outer pass loop runs from i = 0 to n - 2; inner loop shrinks to n - 1 - i.
- Avoid Arrays.sort() in ICSE Section B unless the question explicitly permits library sorting.
3. Dry-Run Trace and ICSE Section B Presentation Rules
Consider the input 'Java makes coding truly joyful'. Tokenizing produces 5 elements: ['Java', 'makes', 'coding', 'truly', 'joyful']. During Bubble Sort Pass 1 (i = 0), 'Java' compares with 'makes' (negative, no swap), then 'makes' swaps past 'coding', stays behind 'truly', and 'truly' swaps past 'joyful'. Subsequent passes bring 'coding' to index 0 and 'joyful' ahead of 'makes'. The final sorted array becomes ['coding', 'Java', 'joyful', 'makes', 'truly']. For full 15-mark Section B credit, declare descriptive identifiers inside main(), display an input prompt, print single-space-separated output without a trailing space, and append a neat Variable Description Table listing loop counters.
- Check edge case n == 0 when a blank line is entered and display a helpful message.
- Write clear comments before the tokenization step and the Bubble Sort block.
- Include every array, loop index, temporary swap string, and count variable in the VDT.
4. SortSentenceWords.java (BlueJ / ICSE Section B)
import java.util.*;
public class SortSentenceWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine().trim();
StringTokenizer st = new StringTokenizer(sentence);
int n = st.countTokens();
if (n == 0) {
System.out.println("No words entered.");
sc.close();
return;
}
String[] words = new String[n];
int idx = 0;
while (st.hasMoreTokens()) {
words[idx++] = st.nextToken();
}
// Bubble Sort words in case-insensitive alphabetical order
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (words[j].compareToIgnoreCase(words[j + 1]) > 0) {
String temp = words[j];
words[j] = words[j + 1];
words[j + 1] = temp;
}
}
}
System.out.println("Words in alphabetical order:");
for (int i = 0; i < n; i++) {
System.out.print(words[i]);
if (i < n - 1) {
System.out.print(" ");
}
}
System.out.println();
sc.close();
}
}
Verified Console / Dry-Run Output:
Enter a sentence: Java makes coding truly joyful
Words in alphabetical order:
coding Java joyful makes truly
5. CISCE Variable Description Table (VDT) & Dry Run
| Variable | Data Type | Exam Purpose & Sample Value |
|---|---|---|
| sentence | String | Stores trimmed input line, e.g. "Java makes coding truly joyful" |
| n | int | Total number of words returned by st.countTokens(), e.g. 5 |
| words | String[] | Array storing extracted tokens; sorted to ["coding", "Java", "joyful", "makes", "truly"] |
| idx | int | Array insertion index incremented from 0 to 4 while loading tokens |
| i, j | int | Outer pass counter (0..3) and inner adjacent-comparison index (0..3-i) |
| temp | String | Temporary swap variable holding words[j] during reordering, e.g. "makes" |
Master ICSE String Tokenizing & Sorting in 1-on-1 Live Classes
Practice StringTokenizer, manual substring extraction, and Bubble Sort dry runs live in BlueJ with an ICSE Java mentor so every 15-mark Section B string question feels routine.
6. Common Mistakes & Top Scorer Tips
- Avoid Mistake: Using sc.next() instead of sc.nextLine(), which captures only the first word and ignores the rest of the sentence.
- Avoid Mistake: Writing words[j] > words[j + 1] in Javaβrelational operators work on primitive characters or numbers, not String objects.
- Avoid Mistake: Calling compareTo() on mixed-case sentences so uppercase 'Java' sorts ahead of lowercase 'coding' due to ASCII code values.
- Examiner / Mentor Tip: If your school teacher prefers manual extraction over StringTokenizer, append " " after trim() and slice words using indexOf(' ').
- Examiner / Mentor Tip: Always mention why compareToIgnoreCase() returns a positive, negative, or zero int if asked in Section A or viva.
- Examiner / Mentor Tip: Write the VDT right below the program with i, j, n, words[], and temp explicitly documented for full documentation marks.
7. Interactive Concept Check Quiz
Question: What does "apple".compareToIgnoreCase("Banana") return in Java, and will Bubble Sort swap them if "apple" is at index j and "Banana" is at j + 1?
8. Frequently Asked Questions
Can we sort words of a sentence in ICSE Java without using StringTokenizer?
Why does Arrays.sort() lose marks in some ICSE Class 10 board solutions?
How do you sort words by length first and alphabetically on ties in Java?
Explore Related Lessons & Free Interactive Tools
- All 110 Guides in ICSE Java BlueJ Library
- Remove Duplicate Characters From a String in Java (BlueJ)
- Reverse Each Word in a Sentence in Java (Without Reversing Word Order)
- Count Double Letter Sequences in Java (ICSE RABBIT / SHEEP Problem)
- Interactive Tool: ICSE Class 10 Java BlueJ Output Quiz
- Interactive Tool: ICSE Variable Description Table (VDT) Auto-Formatter
