Sort String Array (Cities & Names) Using Bubble Sort in Java

⚡ Direct Answer & Key Takeaway

Because Java forbids `<` or `>` on `String` objects, sorting city names or student lists with Bubble Sort requires `compareTo()` or `compareToIgnoreCase()`. Evaluating `cities[j].compareToIgnoreCase(cities[j+1])` returns a positive integer whenever `cities[j]` follows `cities[j+1]` alphabetically. Swapping those two references with a `String` `temp` variable whenever the return value exceeds `0` puts the array in A-to-Z dictionary order, whereas `<` `0` produces Z-to-A reverse dictionary order across all `n-1` passes.

1. How compareTo() & compareToIgnoreCase() Rank Two Strings

Lexicographical comparison works just like looking up words in a printed dictionary, checking character Unicode values from index `0` rightward until a mismatch appears. For `"Pune"` and `"Patna"`, `'P'` matches `'P'`, so Java compares `'u'` (Unicode `117`) against `'a'` (Unicode `97`) and returns `117 - 97 = 20`. Because `20 > 0`, `"Pune"` sits after `"Patna"` and must swap during ascending sort. However, uppercase letters (`65`–`90`) precede lowercase letters (`97`–`122`) in ASCII/Unicode, so `"delhi".compareTo("Agra")` gives `100 - 65 = 35`, yet `"agra".compareTo("Delhi")` also gives `97 - 68 = 29`! Using `compareToIgnoreCase()` prevents mixed-case city names from sorting out of natural alphabetical order.

  • `s1.compareTo(s2) > 0` means `s1` is lexicographically greater (comes later) than `s2`.
  • `s1.compareTo(s2) < 0` means `s1` comes earlier than `s2`; `0` means both strings have identical characters.
  • Prefer `compareToIgnoreCase()` when user input may mix cases such as `"mumbai"` and `"Jaipur"`.
  • If one string is a prefix of another (e.g., `"Goa"` vs `"Goa City"`), `compareTo()` returns `len1 - len2` (`-5`).

2. Handling Scanner Input for Multi-Word City Names

A classic BlueJ runtime trap occurs when reading `int n = sc.nextInt();` followed immediately by `sc.nextLine()` for names like `"New Delhi"` or `"Port Blair"`. Calling `nextInt()` leaves the trailing Enter newline (`\n`) inside the input buffer, causing the very first `nextLine()` call to capture an empty string `""` and skip one city. Adding a dummy `sc.nextLine();` right after `sc.nextInt()` flushes that leftover newline cleanly. If every city or name is strictly one word, `sc.next()` skips whitespace automatically, but ICSE city-sorting questions often test multi-word cities, making buffer flushing with `nextLine()` the safest habit.

  • Always place `sc.nextLine();` once after `sc.nextInt()` before looping to read full-line city names.
  • Use `sc.nextLine()` instead of `sc.next()` so spaces inside `"New Delhi"` or `"Sri Nagar"` stay intact.
  • Declare `String temp;` (never `int temp;`) when swapping elements inside a `String[]` array.

3. Tracing City Array Passes for ICSE Section A & B

Suppose a user enters five city names: `{"Kochi", "Agra", "Pune", "Jaipur", "Bhopal"}`. In Pass 0 (`i = 0`), adjacent comparisons move `"Pune"` rightward until it locks at index `4`, yielding `{"Agra", "Kochi", "Jaipur", "Bhopal", "Pune"}`. In Pass 1 (`i = 1`), `"Kochi"` compares greater than both `"Jaipur"` and `"Bhopal"`, bubbling to index `3` and producing `{"Agra", "Jaipur", "Bhopal", "Kochi", "Pune"}`. Pass 2 (`i = 2`) swaps `"Jaipur"` past `"Bhopal"` into `{"Agra", "Bhopal", "Jaipur", "Kochi", "Pune"}`. Pass 3 checks `"Agra"` against `"Bhopal"`, finds them ordered, and completes the alphabetical list.

  • Each pass pushes the alphabetically last remaining city name toward index `n - 1 - i`.
  • To sort names in Z-to-A descending order, simply invert the test to `compareToIgnoreCase(...) < 0`.
  • If the board question asks for paired arrays (e.g., city and STD code), swap both `cities[j]` and `std[j]` inside the same `if` block.

4. BubbleSortCities.java (Alphabetical String Array Sort)

import java.util.*;

public class BubbleSortCities {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of cities: ");
        int n = sc.nextInt();
        sc.nextLine(); // Clear leftover newline after nextInt()

        String[] cities = new String[n];
        System.out.println("Enter " + n + " city names:");
        for (int i = 0; i < n; i++) {
            cities[i] = sc.nextLine();
        }

        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - 1 - i; j++) {
                if (cities[j].compareToIgnoreCase(cities[j + 1]) > 0) {
                    String temp = cities[j];
                    cities[j] = cities[j + 1];
                    cities[j + 1] = temp;
                }
            }
        }

        System.out.println("Cities in Alphabetical Order:");
        for (int i = 0; i < n; i++) {
            System.out.println(cities[i]);
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter number of cities: 5
Enter 5 city names:
Kochi
Agra
Pune
Jaipur
Bhopal
Cities in Alphabetical Order:
Agra
Bhopal
Jaipur
Kochi
Pune

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
nintStores total count of city names to sort (Sample: 5)
cities[]String[]Stores input and alphabetically sorted city names (Sample: {"Agra", "Bhopal", ...})
iintOuter loop pass counter running 0 to n - 2 (Sample: 0 to 3)
jintInner loop index comparing cities[j] and cities[j+1] (Sample: 0 to 3)
tempStringTemporary string reference used for swapping two cities (Sample: "Kochi")
🎯 1-on-1 Live Mentorship & Free Study Kit

Debug String Arrays & compareTo() Live With an ICSE Mentor

Book a 1-on-1 BlueJ session to master Scanner buffer handling, parallel String-and-marks sorting, and Section A compareTo() dry runs before your board exam.

💬 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: Writing `cities[j] > cities[j + 1]` in Java, which fails to compile because relational operators cannot compare `String` references.
  • Avoid Mistake: Forgetting `sc.nextLine()` after `sc.nextInt()`, causing `cities[0]` to store a blank line `""` and leaving the last city unread.
  • Avoid Mistake: Checking `compareTo(...) == 1` instead of `> 0`; `compareTo()` returns the Unicode character difference (such as `20` or `3`), almost never `1`.
  • Examiner / Mentor Tip: If the ICSE question mentions 'ignoring case' or mixes uppercase/lowercase names, always use `compareToIgnoreCase()` instead of `compareTo()`.
  • Examiner / Mentor Tip: When asked to sort parallel arrays (like 10 student names with their marks), swap `names[j]` and `marks[j]` together inside the same `if` block.
  • Examiner / Mentor Tip: In Section A output questions, remember `'A'` (`65`) and `'a'` (`97`) differ by `32`, so `"Zebra".compareTo("apple")` returns `-7` (`90 - 97`).

7. Interactive Concept Check Quiz

Question: What does the Java expression "Delhi".compareTo("Agra") return, and should Bubble Sort swap them for A-to-Z order?

8. Frequently Asked Questions

Why does compareTo() return a number like 3 or -14 instead of true or false?
Java's compareTo() returns an int indicating both order and Unicode distance at the first mismatching character. A positive integer means the calling string comes later alphabetically, a negative integer means it comes earlier, and zero means both strings are identical. Always check > 0 or < 0, never == 1 or == -1.
Should I use compareTo() or compareToIgnoreCase() in ICSE board exams?
Use compareToIgnoreCase() whenever names or cities may start with mixed uppercase and lowercase letters, because standard compareTo() places every uppercase word like "Zebra" before lowercase "apple". If the question guarantees all inputs are in uppercase or explicitly tests ASCII order in Section A, standard compareTo() gives exact Unicode differences.
How can I sort an array of 10 names in descending Z-to-A order?
Keep the exact same nested Bubble Sort loops and temp String swap, and only change the comparison condition from cities[j].compareToIgnoreCase(cities[j + 1]) > 0 to cities[j].compareToIgnoreCase(cities[j + 1]) < 0. Whenever the left city comes earlier in the alphabet, it moves rightward toward the end.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class