String Sorting Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

Yes. So an array of String references can be sorted.

String Sorting Program

Here is a program that demonstrates how sort() is used with an array of String references. The

import java.util.Arrays;

class ArrayDemoTwo
{
  public static void main ( String[] args )
  {
    String[] animals = {"bat", "fox", "gnu", "eel", "ant", "dog", "fox", "gnat" };
    
    System.out.print("Scrambled array:  ");
    for ( int j=0; j < animals.length; j++ )
      System.out.print( animals[j] + " ");
      
    System.out.println();
    
    Arrays.sort( animals );
    
    System.out.print("Sorted    array:  ");
    for ( int j=0; j < animals.length; j++ )
      System.out.print( animals[j] + " ");
      
    System.out.println();
       
  }
}

The output of the program is:

Scrambled array:  bat fox gnu eel ant dog fox gnat
Sorted    array:  ant bat dog eel fox fox gnat gnu

QUESTION 14:

What is required if sort() is to be used with a class that you define?