Java Reference
In-Depth Information
Chapter 8
Arrays
OBJECTIVES
• Learn how to declare an array variable.
Understand that Java treats an array as an object.
• Learn how to create an array and store its name in a variable.
• Learn how to initialize array elements and reference them.
Look at an array as a way to store a table of data of the same type.
• Learn fundamental algorithms for searching, sorting, and maintaining arrays.
INTRODUCTION
Suppose a program has to maintain information about students enrolled in a uni-
versity. It is infeasible to declare a separate variable for each student! The Java
array —a list of variables of the same type— can be used in such situations.
8.1
Arrays of subscripted variables
The diagram below shows an array variable b and an array object a0 , which con-
sists of four elements of type int :
Activities
8-1.2..3
a0
b a0
0
1
2
3
5
7
4
-2
The four variables are called the elements of the array, and as indicated in the
above diagram, they are numbered 0 , 1 , 2 , and 3 . They are referenced individu-
ally using the notation b[0] , b[1] , b[2] , and b[3] . Mathematical notation writes
the numbers below the line, as in b 2 , and calls the numbers subscripts . Similarly,
Search WWH ::




Custom Search