Review: array of primitive variables

Previously, we learned how to create an array of primitive typed variables:

   double[] numbers; 
 
          Result:   

   numbers = new double[100];
      
          Result:    

Note:   numbers[i] is a double variable and can store a number

Array of of reference variables that point to objects

Similiarly, you can create an array of reference variables:

   Circle[] circleArray; 

          Result:   

   circleArray = new Circle[10];
                         
          Result:    

Note:   circleArray[i] is a Circle reference variable and can store a reference to a Circle object

Array of of reference variables that point to objects

In other words: we can create a Circle object with new and assign it to an array element:

   circleArray = new Circle[10];
                             
      Result:        

   circleArray[0] = new Circle(4);
                             
      Result:          

Note:   circleArray[i] is a Circle reference variable and can store a reference to a Circle object

Contrasting an array of primitive type variables and an array of reference type variables

What is an array of primitive typed variables and an array of reference variables:

  • After creating an array of primitive variables, each array element can store a value:

        double[] numbers = new double[100];
    
        numbers[0] = 99; // We can store a number
     

  • After creating an array of reference variables, each array element can store a reference of an object:

        Circle[] circleArray = new Circle[10];
    
        circleArray[0] = new Circle(2.0); 
                 // Stores a reference to a circle object
    
    

Contrasting an array of primitive type variables and an array of reference type variables

The use of primitive type variables and reference type variables are different:

  • Primitive type array variables (number[k]) contains values and is used in computations:

        double[] numbers = new double[100];
    
        numbers[0] = 99;
        sum = sum + numbers[0]; // number[0] is a double

  • Reference type array variables (circleArray[k]) contains references and is used with the member selection operator  . :

        Circle[] circleArray = new Circle[10];
    
        circleArray[0] = new Circle(2.0); 
        double area = circleArray[0].getArea();
                      // circleArray[0] is a Circle reference

Using an array of objects

  • Array of objects is frequently used in computer programs

  • In the next set of slides, I will show you how to use an array of Card to represent a deck of playing cards