#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Thorsten says:

    You can use this too:
    int[] arr = new[] { 1, 2, 3 };

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: