Search this site


 Java for beginners (topic index)  Variables  for (loops)  if  else  logical operators  arrays  objects

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:

  • put the random numbers into an array, then print the numbers out from the array;
  • show a simple way of sorting an array, so that the random numbers come out in numerical order.

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.

comments powered by Disqus

Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved.