More on Java arrays

In the previous two sections, we looked at arrays, which are a way of setting aside a "row of pigeon holes" in memory for data, and objects, which allow us to create some piece of data in memory and tie it to the methods or routines that act on that data. As an example of an object, we looked at a random number generator class called Random, and how it has a method called nextInt() which allows us to generate random integers (whole numbers) from that Random object.

In our example program, we printed out the random numbers that we generated. In the examples that follow, we're going to:

Putting the numbers into an array

The first example is mostly a reminder of what we've seen before in our introduction to Java arrays. We declare an array of the right size to hold the random numbers we want to generate. In this case, let's say 20:

int[] randomNumbers = new int[20];

Now, we create our Random object as before, and pull out random numbers from it by calling nextInt(). To put an item into the array, we have to say where in the array we put it— i.e. give the position or index (in effect, the "pigeon hole number" in the row of memory). So to put the numbers into consecutive positions until we've filled the array, we use a for loop:

Random rand = new Random();
for (int i = 0; i < randomNumbers.length; i++) {
  int n = rand.nextInt(100);
  randomNumbers[i] = n;
}

Note in this case, our random numbers will be between 0 and 99 inclusive. Notice also the use of randomNumbers.length: length is a special keyword that we can use to query the length of a given array. So our loop sets i to consecutive indicies between 0 and (length - 1)— recall that array indices start at 0, so in fact our 20-position array is numbered from 0 to 19 inclusive.

Now that we've filled our array with random numbers, we can print out those random numbers as follows:

for (int i = 0; i < randomNumbers.length; i++) {
  System.out.println("Position " + i + " : " + randomNumbers[i]);
}

If you put the above fragments together, and run the program, you should find it outputs a list of 20 random numbers.

On the next page, we look at sorting the array.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.