<< Chapter < Page | Chapter >> Page > |
// Learning Object Array01B
// array objectspublic class Array01B {
private final static int SIZE = 7; public static void main(/*String[] args*/) { int[] fib = new int[SIZE];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < fib.length; i++)
fib[i] = fib[i-1] + fib[i-2];
}}
This program combines the declaration of the
array field with its allocator. We have used the constant
SIZE
to
specify the size of the array; this makes it easier to modifythe program; nevertheless,
fib.length
is still used in the
executable statements.
SIZE
is created in the constant
area and given its value.Exercise Modify the program so that the fibonacci sequence appears in reverse order.
Concept An array object can be created implicitly by giving a list of values within braces.
Program: Array02.java
// Learning Object Array02
// array initializerspublic class Array02 {
public static void main(/*String[] args*/) {
int[] fib = {0, 1, 1, 2, 3, 5, 8};
}}
The program initializes an array with values of the fibonacci sequence.
fib
of type integer array (denoted
int[]
) is allocated.fib
.Exercise Can an element of an array initializer be the value of an expression containing variables previously declared? Modify this programaccordingly and try to compile and run it. Explain what happens.
Concept An array is an object. Since the array variable itself contains a reference, it can be passed as an actual paramter to a methodand the reference is used to initialize the formal parameter.
Program: Array03.java
// Learning Object Array03
// passing arrays as parameterspublic class Array03 {
static void reverse(int[] a) {
int temp,j; for (int i = 0; i < a.length / 2; i++) {
j = a.length-i-1; temp = a[i]; a[i] = a[j];
a[j] = temp;
} }
public static void main(/*String[] args*/) { int[] fib = {0, 1, 1, 2, 3, 5, 8}; reverse(fib);
}}
This program passes an array as a parameter to a method that reverses the elements of the array.
fib
of type integer array is
allocated. As part of the same statement, the array object is created withits seven fields having the values in the initializer; the reference to
the object is returned and stored in the variable
fib
.reverse
. There are now two arrows pointing to the array: the reference from the
main
method and the reference from the parameter
a
of the method
reverse
.i
and
j
contain the indices of the two elements that are exchanged.fib
still
contains a reference to the array, which has had its sequence of valuesreversed.Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?