Title: Array Fundamentals1
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Array Fundamentals 1

Array Fundamentals

1. What are arrays ... a collection of similar things. The "Things" can be primitives or classes.


// Allocating array space
  double[] score = new double[3];  // Note this is not (3) as in the constructor case
  // As opposed to:
  Scanner keyboard = new Scanner(System.in);


2. The above can be done as a 2-step process


  // Declaring an array variable:
  double[] score ; // takes on a reference value of null and equivalent to the following:
  double[] score2=null;
  // Compiler knows about the array variables score and score2, but no memory has been
  // allocated for either variable at this point
  //....

   score = new double[3];  // some time later we allocate the space
// default values after above statement is 0 for all 3 locations
  for (int i=0; i < 3; i++)
     System.out.println(score[i]);

// Need to draw a picture of the memory allocated.

// Arrays act like objects. We use references for arrays like we do for class
//    objects. The book makes a strong case that arrays are similar to classes.
//    Note that we use "new" for arrays as well as classes.


3. Initializing our array


  double[] score= new double[3];
  score[0] = 10;
  score[1] = 11;
  score[2] = 12;
 //score[3] = 13; // Error case. Note that the compiler doesn't catch this,
                  // but a runtime error occurs ... try it out.
  //Or with a for loop:
  for (int i=0; i < 3; i++)
     score[i] = 10+i;

// what happens if our for loop condition above is "i <= 3"


  // We can read in values for the above scores:
  System.out.println("Enter in 3 numbers");
  Scanner keyboard = new Scanner(System.in);
  for (int i=0; i < 3; i++)
      score[i] = keyboard.nextDouble();
	  	
  // Now we can reference the values as follows:
  double d0, d1, d2, d3, d4, d5;
  d0 = score[0];   // Note that score[0] is equivalent to a double
  d1 = score[1];
  d2 = score[2];

  for (int i=0; i < 3; i++)
  {
    double d = score[i];
    System.out.println(d);
  }


4. Note that "score.length" can be used to avoid repeating "3" everywhere above. The property score.length contains the number of entries in the score array.
Legal indices to an array are always 0, 1, 2, .... length-1
5. Note that length cannot be changed by you directly
// Can't do the following
score.length = 10; // Compile error on this
6. What happens in our last example, if we add a statement in the latter part of the program that looks like:

d = new double[6];
// Draw a picture and talk about "orphaned memory"
7. Common errors occur in accessing the end of the array and sometimes the beginning of the array.
Often for loops are used when we are going through an array.
An array created as follows:
String[] page = new String[5];
// The legal indices to page are 0, 1, 2, 3, 4
8. If you access an index that doesn't exist, your program will abort with an Exception
9. In the previous example, anywhere you can use a double, you can use:
score[2]
Arrays of Classes
10. If you understand the concept for double above, the idea of an array applies to any data type:


int[] line = new int[80]; // Initially the array will contain all zero's

// Note that in the following, the 55 page Strings are initialized to null.
// You need to call constructors to create the Strings

 String[] page = new String[55];
 String s = page[0];
 int len = s.length(); // Runtime error occurs
 //... Draw picture of the current state for the Array of Strings.


11. Classes need to be initialized after creating array space. (You will need the Date class from chapter 4)


// Redo the previous example where we set:
String[] page = new String[55];
page[0]="abc";
page[1] = "xyz";

String s = page[0];
int len = s.length(); // NO Runtime error occurs NOW
// Draw a picture

//Redo the above with the Date class
//Note that the following doesn't blow up because println is forgiving:
Date[] dates = new Date[3];
System.out.println("First date="+ dates[0]);

//But try to run it with
int month = dates[0].getMonth();


12.
//Repeat again after setting
Date[] dates = new Date[3];
dates[0] = new Date(1,2,2012);
dates[1] = new Date(4,8,1984);
dates[2] = new Date(7,3,1987);
for (int i=0; i < dates.length; i++)
    System.out.println(dates[i]);
//Draw pictures of the Array of Dates.

	//  Consider another class you might make:
//   Person[] persons = new Person[10];
	

13. See the book for ArrayOfScores.java(chapter 6) ... for loops and arrays go together well.


import java.util.Scanner;

public class ArrayOfScores
{
    /**
     Reads in 5 scores and shows how much each
     score differs from the highest score.
    */
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        double[] score = new double[5];
        int index;
        double max;

        System.out.println("Enter 5 scores:");
        score[0] = keyboard.nextDouble( );
        max = score[0];
        for (index = 1; index < 5; index++)
        {
            score[index] = keyboard.nextDouble( );
            if (score[index] > max)
                 max = score[index];
        //max is the largest of the values score[0],..., score[index].
        }

        System.out.println("The highest score is " + max);
        System.out.println("The scores are:");
        for (index = 0; index < 5; index++)
            System.out.println(score[index] + " differs from max by "
                                            + (max - score[index]));
    }
}


14. In the ArrayOfScores.java example, make use of .length.

Last Modified: November 26, 2014 11:05 AM