Creating an Array of Primitives

When creating an array of primitives, the third step does not include using new because primitives are not created with new and do not have constructors. The third step is just to set the values.

  1. Declare the reference, or array variable.
    	int	nums[];
    

  2. Allocate the slots for the array with new.
    	nums = new int[25];
    

    Note that we are using new to allocate the slots in the array. We are not using new to create integers.

  3. Set the elements, using an assignment statement.
    	nums[0] = 7;
    

We can also use a loop to set an array. Let's suppose we want to fill an array of ints with random numbers. The code in below illustrates this.


	int	randList[] = new int[200];
	int	i;
	Random	r = new Random();

	for (i = 0; i < randList.length; i++)
		randList[i] = r.nextInt();

Note that since we are filling the array, we use the length instance variable in our loop. If later we changed our code so the array was 500 instead of 200, the rest of our code would not change. This brings up an important rule that you can follow when working with arrays: When you mean the size of the array, use the length instance variable. Imagine that we had a very big program that uses this array, if we had used the number 200 instead of randList.length, we would break a lot of code once we changed the array's size to 500.


Last Updated - 09/15/2020 06:10:41