<< Chapter < Page | Chapter >> Page > |
Concept An array is a sequence of elements of the same type;
the type of the elements can be a primitive types such as
int
,
or a predefined or user-defined class type. To access an element of an array, an index is given; this may be any expression of type
int
, including an integer literal or a variable.
The source code of these learning objects can be found in array.zip .
LO | Topic | Java Files (.java) | Prerequisites |
"Array objects" | Array objects | Array01A, B | |
"Array initializers" | Array initializers | Array02 | 1 |
"Passing arrays as parameters" | Passing arrays as parameters | Array03 | 2 |
"Returning an array from a method" | Returning an array from a method | Array04 | 2 |
"Array assignment can create garbage" | Array assignment can create garbage | Array05 | 4 |
"Two-dimensional arrays" | Two-dimensional arrays | Array06 | 3 |
"Arrays of arrays" | Arrays of arrays | Array07 | 6 |
"Ragged Arrays" | Ragged arrays | Array08 | 6 |
"Arrays of objects" | Arrays of objects | Array09 | 3 |
The example used in LO 1 through LO 4 is to fill an array with a sequence of fibonacci numbers (0,1,1,2,3,5,8). The programs forLO 5 through LO 8 concern matrices. The program for LO 9 is explained there.
Concept An array is created in three steps: first a variable of
an array type is declared; then the array is allocated; finally, theelements of the array are given values. The syntax for accessing an array
a
is
a[i]
, and the field
a.length
gives the
length of the array, so that if we modify the program by changing the sizeof the array the rest of the program need not change.
Program: Array01A.java
// Learning Object Array01A
// array objectspublic class Array01A {
public static void main(/*String[] args*/) {
int[] fib;
fib = new int[7];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < fib.length; i++)
fib[i] = fib[i-1] + fib[i-2];
}}
The program creates an array in the three steps described above.
fib
of type integer array (denoted
int[]
) is allocated and contains the null value.new fib[7]
creates an array object with its seven fields having the default
integer value zero; then the reference to the object is returned and
stored in the variable
fib
.for
loop is used to assign values to each element of the
array.fib[i-2]
seem to indicate that
fib
is being indexed,
fib
contains a reference to an array;
an implicit operation of dereferencing is carried out to obtain thearray itself from the reference and the index
[i-2]
is then
applied to that array.Concept It is possible to combine the first two steps in creating an array: declaring the array field and allocating the array object.
Program: Array01B.java
Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?