The StringTest class:

Here is a program that solves Part 2 of the Review for Exam 2:

// StringTest.java: Review question 2, about arrays of Stringt 

public class StringTest {

   public static void main (String[] args) {
      // Review part 2.a. 
      String[] fruits = {"banana", "orange", "grapefruit",
                      "strawberry", "apple", "melon"};
      printArray("Part 2.a.", fruits);
      // Review part 2.b.  
      fruits[5] = "watermelon";
      printArray("Part 2.b.", fruits);
      // Review part 2.c.
      String first = fruits[0];  
      for (int i = 1; i < fruits.length; i++)
         if (first.compareTo(fruits[i]) > 0) first = fruits[i];
      System.out.println("Part 2.c.:  First fruit: " + first);
      // Review part 2.d.  
      SortStrings.insertionSort(fruits);
      printArray("Part 2.d.", fruits); 
   }

   private static void printArray(String heading, String[] f) {
      System.out.print(heading + ":  Array fruits: ");
      for (int i = 0; i < f.length; i++)
         System.out.print(f[i] + " ");
      System.out.println();
   }
}

/* output:

Part 2.a.:  Array fruits: banana orange grapefruit strawberry apple melon
Part 2.b.:  Array fruits: banana orange grapefruit strawberry apple watermelon
Part 2.c.:  Last fruit: apple
Part 2.d.:  Array fruits: apple banana grapefruit orange strawberry watermelon

*/


And here is the code for sorting strings: just the book's insertionSort modified to handle strings.

// SortStrings.java: sort an array of Strings
public class SortStrings {

   // insertionSort: keep inserting at the proper position
   public static void insertionSort (String[] s) {
      for (int index = 1; index < s.length; index++) {
         String key = s[index];
         int position = index;

         // shift larger values to the right     
         while (position > 0 && key.compareTo(s[position-1]) < 0) {
            s[position] = s[position-1];
            position--;
         }

         s[position] = key;
      }
   }
}


Revision date: 2003-11-09. (Please use ISO 8601, the International Standard.)