您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 3

What is an array?

An array is a way of storing, retrieving and changing a sequence (i.e. ordered collection) of variables that are all the same type. An array has an identifier (name), stores elements all of the same type, and has an unchanging size (dimension).

The figure below illustrates an array deliveries, which stores 5 elements, each of type int. Each element of the array represents how many deliveries were made by a courier in a working week.

deliveries[]
element
value
deliveries[0]
14
deliveries[1]
17
deliveries[2]
22
deliveries[3]
9
deliveries[4]
16
Notice how each of the 5 variables stored in this array (the 5 elements of the array) are referred to by a combination of the array identifier and the element number (index) inside square brackets. Also notice how the first element of the array has index 0, rather than 1. Forgetting this feature of arrays leads to many simple errors when learning to use them.
To declare an array, one must state the type of variables that will be stored within it, and the identifier of the array. 

Imagine we are developing a software system for a restaurant, and we need to be able to store the number of people who have pre-booked for each evening. For example, if we wish to store all the bookings for the coming week, we need to store and work with 7 intvariables. Rather than have seven different variables, we can work with an array of 7 intvariables. We shall call this array bookings. For example, the following line:

int bookings[]; declares an array with the identifier bookings, that can refer to a sequence of intvariables.

Once declared, an array needs to have its size defined. For example, we can define our bookingsarray to store 7 intvariables as follows:

bookings = new int[7];
To refer to a particular element (variable) in an array, we need to specify the array identifier and the index of the array element in which we are interested. So, for example we display the first booking as follows:
System.out.println( booking[0] );

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg