Declaring an Array

When you create an array, you will need to do three steps:

  1. Declare the reference, or array variable.

  2. Allocate the slots for the array with new.

  3. Create the elements in the array with new (unless it is an array of primitives).

Example

  1. Declare the reference, or array variable.
    	Color	colorList[];
    

    The square brackets indicate that the variable called colorList is an array of class Color. You can also put the brackets before the identifier name.

    	Color	[] colorList;
    

    If you wish to declare multiple arrays, each one must have its own set of brackets.

    	Color	colorList1[], colorList2[];	// declares 2 arrays
    	Color	[] colorList3, colorList4;	// declares 1 array and 1 Color object
    	Color	colorList5[], colorList6;	// declares 1 array and 1 Color object
    

    In this example code, colorList1, colorList2, colorList3,and colorList5 all have a data type of array of Color. colorList4 and colorList6 both have a data type of Color because they don't have the square brackets.

  2. Allocate the slots for the array with new.
    	colorList1 = new Color[3];
    

    The number in the square brackets indicates how big the array is. You can access the size of the array with the length member variable. This code will printout the number 3.

    	System.out.println(colorList1.length);
    

    You can combine the first two steps into one statement of code.

    	Color colorList2[] = new Color[5];
    

    This declaration creates the colorList2 array object amd allocates the array to hold up to 5 Color objects. Note that although it is one statement, both Step 1 (declare the array variable) and Step 2 (allocate the slots) are begin done.

  3. Create the elements in the array with new.
    	colorList1[0] = new Color(187, 0, 0);	// red off
    	colorList1[1] = new Color(187, 187, 0);	// yellow off
    	colorList1[2] = new Color(0, 100, 0);	// green off
    

    Each of these statements creates a new color object by calling the constructor for the Color class that takes 3 arguments. The corresponding array element refers to each of these new colors.

    If you want to set one of the elements to the built-in colors, don't use the new. The built-in color are class variables, meaning that they already exist and there is only one of each of them. For instance, the class variable Color.red is of class Color and represents red (RGB of 255, 0, 0). There is only 1 Color.red, so you don't create it with new. If we wanted to use the built-in colors for red, yellow, and green, our code would not have the new. We can mix custom colors with the built-in colors.

    	colorList2[0] = new Color(187, 0, 0);
    	colorList2[1] = Color.red;
    	colorList2[2] = Color.blue;
    	colorList2[3] = new Color(0, 122, 122);
    	colorList2[3] = Color.yellow;
    

The steps for setting an array of primitives is sligthly different, so let's discuss arrays of primitives.