Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)

9.7 Using Arrays in Java

In Java, arrays are really defined as objects. They have to be declared as an object reference, and then it must be created with the appropriate number of elements.

The general Java statement to declare and create an array is:

〈 array_type 〉 [] 〈 array_name 〉 = new 〈 array_type 〉 [ 〈 capacity 〉 ];

For example, the Java declaration of array temp of type float and with a capacity of 10 elements is:

float[] temp = new float [10]; . . .

The declaration of an array of object references is the same as the declaration of object references—the array type is a class. For example, the Java declaration of array employees of class Employee and with 50 elements of capacity is:

Employee employees = new Employee [50]; . . .

The referencing of individual elements is carried out with an appropriate index, as explained before. For example, to assign a value of 342.65 to element 7 of array temp, the Java code is:

temp[6] = 342.65;

Because an array is an object in Java, there is a particular public attribute of arrays that is very useful and that stores the capacity of the array. The name of this attribute is length. To access this attribute, the dot notation is used with the name of the array. For example, to assign a value 0.00 to every element of array temp, the Java code is:

for (j = 0; j < temp.length; j++) temp[j] = 0.00;

To create an object of class Employee and assign its reference to the element with index j of array employees, the Java code is:

employees[j] = new Employee();

To invoke a public function of an object referenced in an element of an array, the dot notation is used; the name of the array is followed by a dot and followed by the name of the function. For example, to invoke the function get_salary of the object referenced by an element with index j in array employees, the Java code is:

float obj_salary; int j; . . . obj_salary = employees[j].get_salary();

Категории