#1,012 – Options for Array Declaration, Instantiation and Initialization

Recall that there are three steps for using arrays:

  • Declare the array (declare a variable whose type is an array)
  • Instantiate the array (allocate memory for the array)
  • Initialize the array (store values in the array)

Below are examples of the different ways that you can declare, instantiate, and initialize an array.

            // Option 1: Declare, instantiate and initialize in three
            //   steps
            int[] a1;
            a1 = new int[3];
            a1[0] = 1; a1[1] = 2; a1[2] = 3;

            // Option 2: Declare in 1 step, instantiate/initialize in
            //   2nd step
            int[] a2;
            a2 = new int[] {1, 2, 3};

            // Option 3: Declare and instantiate in 1 step,
            //   initialize later.
            int[] a3 = new int[3];  // Must provide size
            a3[0] = 1; a3[1] = 2; a3[2] = 3;

            // Option 4: Declare, instantiate and initialize
            //   in single line. (Using array initializer)
            int[] a4 = new int[] { 1, 2, 3 };

            // Variation: Can omit type
            int[] a5 = new[] { 1, 2, 3 };

            // Variation: Can omit new keyword, inferring type
            int[] a6 = { 1, 2, 3 };
Advertisement