Return to lecture notes index

15-100 Lecture 24 (Monday, October 31, 2005)

Quick Quiz

Given the add() method below, please cause a NegativeNumberException to arise if a negative number is provided as either argument to the method.

class Quiz {

    public class NegativeNumberException extend Exception {
      public NegativeNumberException (String message) {
        super (message);


    //a NegativeNumberException should arrise when number1 or 
    //number2 is negative
    public static int add(int number1, int number2) 
      throws NegativeNumberException {
        // if ( (number1 < 0) || (number2 < 0) )
        if (number1 < 0) 
          throw new 
             NegativeNumberException ("Arguments to add() should be postive");
        if (number2 < 0)
             NegativeNumberException ("Arguments to add() should be postive");

        return number1 + number2;


Introduction to Arrays

So far, whenever we've wanted to have a collection of objects, we've had to hardcode declare each of the objects individually, and reference each individually. There's been no relation between the members of the collection, and they cannot be referenced as a set. We had had no way of iterating through them. They are not linked. There was no way to automatically make an x number of Objects.

   String s1;
   String s2;
   String s3;
   String s4;

Random Access collection: want to make the 1 through 4 a referance intead of part of the reference variable's name. It would be the index.

Today, we're going to learn a data structure that can hold a collection of Objects or primitives - the array. An array of four Strings can be created as follow:

   String[] names;
   names = new String[4];

'names' is a reference variable to an array of Strings, not to an individual String. The "String []" is the type of object that "names" can refer to. The second line actually creates the array of 4 Strings, and assigns it to the reference variable. Note that you must specify a size of the array when you create it. This size is the number of cells in the array; the max number of Strings that the array 'names' can hold. Note that we use brackets in order to declare an array, it's size, and to reference the index (see below).

Because Strings are Objects, not primitives, names is actually a reference to an array of String references, not actual Strings. In order to access these individual String references, we use brackets after the array name to specify an index into the array. For example, to access the element of 'names' at index 0, we would use the syntax, "names[0]".

Java (like C and C++) indexes arrays starting with 0 for the first index. So for an array of size 3, the indexes range from 0 to 2. This is important to remember, because if you try to refer to the first element of the array by accessing names[1], you're actually getting the SECOND element, and if you try to access the last element by accessing names[3], an ArrayOutOfBoundsException will be thrown, because Java knows this element does not exist!

The array 'names' now looks like this:

  names -->  |   null   |   null   |   null   |  null   |
             |          |          |          |         |
               names[0]    names[1]  names[2]   names[3]

All four elements of the array (names[0], names[1], etc.) are references to Strings, but we haven't actually created the Strings and assigned them to the references yet! Therefore, currently, each index of the array stores "null".

To initialize these Strings, we would have to do the following for names[0], names[1], names[2] and names[3] (our four String references):

   names[0] = "Greg";

Once we've done this for names[0], the array looks like this:

               names[0]    names[1]  names[2]   names[3]
  names -->  |    *     |   null   |   null   |  null   |
             |    ||    |          |          |         |
             |  "Greg"  |

There is also a variable for all arrays called length that is publicly accessible. The line "System.out.println(names.length);" will print out 4 because that is the size that we made our array. Note that since we are calling on a public variable and not a method there are no parentheses after length.

Note that we can now understand the familiar signature of main():

class ArrayExample {
  public static void main (String[] args) 

Consider the following code segment as part of main():

  System.out.println("There are " + args.length + " arguments");

  for (int index = 0; index < args.length; index ++){

The args array is a String array that contains the so-called "command-line arguments" to the program. For example, if we ran the program as follows:

  class ArrayExample hi mom and dad and grandpa

...the main shown above prints each of the arguments:

There are 6 arguments

A Bigger Example

Let's do an example...

class ArrayExample {
   public static void main(String[] args) throws Exception {
      // First, let's instantiate our variable as a reference to an array of
      //  Strings.  We'll call it 'names'.
      String[] names;
      // Now, we obtain want size we want our array
      BufferedReader keyboard = new BufferedReader(new InputStreamReader(;
      System.out.println("How many names? ");
      int nameCount = Integer.parseInt(br.readLine);
      // Now, we create a new array of the user entered size of Strings, and assign it to names.
      names = new String[nameCount];
      // We want to prompt the user for the correct number of strings to put into this array,
      // so we'll use a while loop to prompt the user nameCount times.  Each time the
      // user inputs a String, it will assign the String to names[index], which
      // is one of the String references in the array (names[0], names[1],
      // etc.).
      for int index = 0; index < nameCount; index++) {
         System.out.print("Enter name #" + index + ": ");
         names[index] = keyboard.readLine();

      // Now let's use the same method of accessing each index to print out
      // the Strings.
      for(int index = 0; index < nameCount; index++) {
         System.out.println(index + ": " + names[index]);
      //to print out backwards:
      for(int index = (names.length - 1); index >=0; index--){
         System.out.println(index + ": " + names[index]);
      //We can also print out a name at a specific index...
          System.out.print("Which name do you want to print [0..." + (names.length-1) + "] ? ");
          int printIndex = Integer.parseInt(keyboard.readLine());
          //this will cause the program to exit the infinite loop
      //here's a similar example to the above code...only using a variable to cause
      //the loop to exit instead of a "break;" line.  
      boolean done = false
      while (!done){
          // We can also prompt the user to change one of the names, save which
          // index he/she wants to change, and then assign the new name he/she
          // inputs to the array 'names' at the index specified by the user.
          System.out.print("Change which name? ");
          int changeIndex = Integer.parseInt(keyboard.readLine());
          System.out.print("What is the new name? ");
          name[changeIndex] = keyboard.readLine();
          //if it reaches this line without throwing an exception it allows the
          //user to exit the while loop
          done = true;
      // And let's print out the array again, so we can see that the change
      // was actually made.
      for(int index = 0; index < nameCount; index++) {
         System.out.println(index + ". " + words[index]);