Sort Words of a Sentence Alphabetically in Java (ICSE)

⚑ Direct Answer & Key Takeaway

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

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

VariableData TypeExam Purpose & Sample Value
sentenceStringStores trimmed input line, e.g. "Java makes coding truly joyful"
nintTotal number of words returned by st.countTokens(), e.g. 5
wordsString[]Array storing extracted tokens; sorted to ["coding", "Java", "joyful", "makes", "truly"]
idxintArray insertion index incremented from 0 to 4 while loading tokens
i, jintOuter pass counter (0..3) and inner adjacent-comparison index (0..3-i)
tempStringTemporary swap variable holding words[j] during reordering, e.g. "makes"
🎯 1-on-1 Live Mentorship & Free Study Kit

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.

πŸ’¬ WhatsApp Now
πŸ”’ Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

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?
Yes, you can count spaces first after calling trim() and appending a single space at the end, then extract each word using substring(start, i) whenever charAt(i) hits ' '. Once the String array is populated, the exact same nested Bubble Sort loop and compareToIgnoreCase() comparison sorts every word cleanly without relying on StringTokenizer in BlueJ.
Why does Arrays.sort() lose marks in some ICSE Class 10 board solutions?
CISCE Section B questions test whether students can implement sorting and string manipulation algorithms using loops and arrays. Unless a prompt explicitly allows built-in sorting utilities, examiners expect you to write Bubble Sort or Selection Sort alongside compareTo() or compareToIgnoreCase(). Using Arrays.sort() skips the core algorithmic logic being assessed in the 15-mark question.
How do you sort words by length first and alphabetically on ties in Java?
Inside the Bubble Sort condition, first compare words[j].length() > words[j + 1].length() to push shorter words toward the front. Add an else if branch checking words[j].length() == words[j + 1].length() && words[j].compareToIgnoreCase(words[j + 1]) > 0 so equal-length words fall back to alphabetical order. Both conditions trigger the exact same three-line string swap.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class