Academic Java    Java Tutorial  >  Arrays  >  array of objects

array of objects Example

Java array of objects EXAMPLE output This program creates an array of color objects and uses it to provide color for box objects.

The program illustrates that the elements of arrays of objects (reference variables) when created are initialized with null values.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Reference Array Example
import java.awt.*;

class ReferenceArrayExample {

   public static void main(String[] args) {

      Color[] ca;

      ca = new Color[5];
      ca[0] = Color.red;
      ca[1] = Color.blue;
      ca[3] = Color.green;
      ca[4] = Color.magenta;

      for(int i=0; i<ca.length; i++) {
         if(ca[i]==null) continue;

         ABox b = new ABox(ca[i], 50+(i*50), 150, 50, 50);
         b.draw();
      }

   }
}

10-14 The Color[] array is created.
Notice that one element ca[2] has not been given a value. It therefore takes the default null value.

16-21 The loop iterates through the color array.
Notice that the indexed color element is tested for a null value and if it is null is ignored.
This is because a run error would occur if an attempt was made to draw a box with a color whose value was null.