9.3 Arrays of Strings

Like any other objects, strings can be elements of arrays. To create an array of strings holding the names of the seasons of the year, we can start by making the declaration
String[] seasons = new String [4]; 
This creates an array whose four elements are references to objects of type String. Since they are reference types, they will be initialized to null giving the structure illustrated in the next diagram.

The values of the seasons could then be assigned by writing

season [0] = "Spring";
season [1] = "Summer";
season [2] = "Fall" ;
season [3] = "Winter"; 
The results of this are displayed in the next diagram.

All of this could have been accomplished in one step by using the array initializer notation that we have seen many times before. To create and initialize the seasons array, we could write

String[] seasons = {"Spring", "Summer", "Fall", "Winter"}; 
You may have noticed that we have already seen string arrays many times. In fact, you have been using them (probably without realizing it) since your very first program! Every main method in Java starts with a header of the form
public static void main (String[] args) 
The parameter here is a String array called args. Parameters in Java are given the values of their arguments when a method is called. Since the main method is not called from another method, values are given to arguments of the main method somewhat differently than for other methods. To be able to pass argument values to main, you must be able to use a command line interface to run a program. If you are used to running your Java programs in an integrated development environment (IDE), it may be possible to do so from within the IDE but you may have to open a command window. You should check the documentation of your IDE or speak with your system administrator for the details.

Using a command line, we call the main method by writing the word java followed by the name of the class that contains main. If we want to give arguments to main, we can do so simply by writing them on the same line that we use to make the call. Because of this, these arguments are known as command line arguments. They are automatically assigned to the string array parameter of main(usually called args). The first argument is assigned to args[0], the second to args[1] , and so on. Any command line arguments are separated from each other by at least one blank. It is not necessary to surround each argument by double quotes unless we want an argument to contain blanks.

Example 1

A program containing a main method in a class Sample could be called by the command
   java Sample George John Paul Ringo "The Beatles"
This would create an argument array of length five. If the parameter of the main method were called args, then we would have

   args[O] = "George"
    .
    .
   args[4] = "The Beatles"
The quotes around The Beatles (on the command line) ensure that those two words are considered as one string. Without the quotes, we would have
   args [4] = "The"
and
   args [5] = "Beatles"

Command line arguments can represent any type but they are always stored as strings and, if we want to use them for other purposes, we must convert them appropriately. Often, there are methods available to assist us in these conversions. For example, if we want to convert a string to an integer, we can use parseInt, a class method in the Integer class having the header

   public static int parselnt (String s) 
The method returns the integer represented by s. If s does not represent an integer, the method throws a NumberFormatException.

Example 2

Suppose a program contains a main method in a class Update. The program expects a command line giving the date in the form <year> <month> <day>. We could invoke the program by writing
   java Update 2010 12 31
Inside the program, we could convert the arguments to integers by writing
int year = Integer.parseInt(args[O]);
int month = Integer.parseInt(args[l]);
int day = Integer.parseInt(args[2]); 

Parsing methods are available for converting strings to any of Java's numerical types. For example, to convert a string to a double value, we could use the method parseDouble in the Double class. A complete list of these methods is given in the table on page 588.

If a program is expecting a particular form of command line argument, then it is easy to check to see whether or not the user has supplied the appropriate number of values.

Example 3

The following fragment could be used in a main method to check that a user has supplied the three arguments required in the command line.
public static void main (String[] args)
{
   if (args.length != 3)
   {
      System.out.println("Program requires 3 arguments. ");
      System. exit(1);
   }
   else
      // rest of main method

In Example 3, the statement System.exit(1); is used to terminate the program. The exit method of the System class causes a program to stop immediately. An argument of zero is passed to exit on normal termination while some other value (one in our example) is used to indicate abnormal termination.

Exercise 9.3

  1. Complete the definition of the method avLength so that it returns the average length of the strings in its array parameter.
    public static double avLength (String[] list) 
  2. Complete the definition of the method first so that it returns the string that would appear first if the strings of the parameter were placed in lexicographic order.
    public static String first (String[] list) 
  3. Write a fragment that will print the values of a program's command line arguments. They should be printed on one line, separated by commas followed by single blanks. If there are no arguments, an appropriate message should be printed.
  4. A program is expecting command line arguments consisting of a minus sign followed by any number of lower case letters. For example, -ad would be a valid argument. Write a fragment that checks the form of the argument. If there is no argument or if the argument is of the wrong form, the fragment should print an appropriate message and cause the program to terminate.
  5. A simple calculator program is expecting command line arguments that have the form <operand1> <operator> <operand> where both <operand1> and <operand2> are integers while <operator> is one of +, -, *, /, or %. Write a method that will calculate and return the value of <operand1> <operator> <operand2>. For example, if the command line arguments are 5 + 3, the method should return the value 8. Assume that the command line argument values are all valid.