#130 – Default Values of Array Elements

After declaring and instantiating an array, all of its elements take on default values.  The default value for all numeric types is 0 and for all reference types is null.  For enum types, the default value will be the element that has a value of 0–typically the first item listed in the enum.

 float[] nums = new float[4];
 float f1 = nums[0];    // 0.0

 Cat[] pack = new Cat[5];
 Cat c1 = pack[0];      // null

 Days[] someDays = new Days[4];
 Days thatDay = someDays[2];   // Sunday (1st in list)

The same rule applies for default values in a multi-dimensional array.  Each element is 0-valued or null.

 int[,] nums = new int[2, 3];
 int aNum = nums[1, 2];          // 0

With jagged arrays, you typically only instantiate the first dimension.  Elements of that dimension are null.

 int[][] jagged = new int[3][];
 object o = jagged[0];    // null
 int n1 = jagged[0][0];   // Error: NullReferenceException

 jagged[0] = new int[10];
 int n2 = jagged[0][2];    // 0
Advertisement

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

2 Responses to #130 – Default Values of Array Elements

  1. bruce says:

    Days[] someDays = new Days[4];
    Days thatDay = someDays[2]; // Sunday (1st in list)

    Why? Where did “Sunday” get set?

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: