Java Reference
In-Depth Information
The size of an array
The size of an array,also called the array length ,is the number of elements
it contains. The size of an array is defined when the array is created. Once
an array is created,its length cannot be changed. However,arrays can be
created using a variable or an expression to define the number of elements.
Suppose you wrote a program that used an array to store the names of
the passengers in an airline flight,and that the airline operated airplanes
with different seating capacities. One possible solution would be to allo-
cate the array size for the largest aircraft. But this would waste storage
space if the flight was to use a smaller airplane. A more reasonable option
is to let the user of the program determine the size of the array at the time
it is created. The program would question the user about the size of the
aircraft and then allocate the number of elements in the array according
to this value. For example:
int airPlaneSize;
airPlaneSize = inInt(“Enter number of passengers: ”);
String[] passenger = new String[airPlaneSize];
In this case the number of elements of the array passenger[] is deter-
mined by the value of the variable airPlaneSize,which is entered by the
user. When the size of an array is determined as the program executes,we
say that the array is allocated at runtime.
Programs often need to know the size of an array. For example,if you
need to display the names of all the elements in the array passenger[],you
would need to know how many elements were allocated when the array
was created. Since arrays can be allocated at runtime,you are not able to
determine the array size by inspecting the code. The Java length operator
returns the number of elements allocated in an array. For example:
int passengerCount = passenger.length;
In this case the variable passengerCount is assigned the number of ele-
ments in the array passenger[]. The following program demonstrates the
simultaneous declaration and initialization of arrays and the use of the
length operator.
On the Web
The source file for the program ArrayOps.java can be found in the
Chapter 6 folder at www.crcpress.com.
Search WWH ::




Custom Search