Laboratory 8

Arrays

Week of 4 April, 2005


Home | Resources | Homeworks | Slides | Labs | Contacts | Submit | Forums | Private

Objective

A programmer often needs to represent a group of values or objects together in a list. The basic Java list mechanism is the array. When you use a list, you often need to be able to find values in the list. Therefore, we review several search algorithms.

 

Key Concepts

 

Getting Started

Using the procedures in the previous laboratories, copy the files Sum.java and ArrayFun.java for your manipulation.

 

Basics

An array in Java is a list of elements. The list is an object. The individual elements can be accessed through subscripting using the bracket operator []. If a list is composed of n values, then the first element has a subscript value of 0, the second element has a subscript value of 1, and so on with the last element having a subscript value of n-1.

To assist programmers, an array has a public data field named length that specifies the number of elements in the list.

Another form of array assistance is the automatic detection by Java of illegal subscripting – subscripts that are too big or too little. If a subscript is determined to be invalid, an exception of type IndexOutOfBoundsException is generated. As it is with other unhandled exceptions, if IndexOutOfBoundsException occurs and is not handled explicitly by the program, then the program terminates.

The IndexOutOfBoundsException prevents your program from inappropriately accessing memory outside its allocated space. (Attempting illegal memory accesses and assignments is a common exploitation effort of virus writers.)

When writing programs in the future pay attention to the fact that when using a for loop in Java to iterate through an array, the body of loop should typically only iterate when loop indices are in the range 0 to n-1, where n is the size of the array. This design accommodates the fact that Java numbers array indices from 0 to n-1. Hence, the typical for loop initializes its loop control variable to 0 and repeats the loop as long as the index is less than the size of the list.

 

Array manipulations

Open program file ArrayFun.java. This program first determines from its user the size n of a list that is to be extracted. The program then extracts n values from the standard input stream and uses them to set the values of the elements of array number[]. The program then determines and displays the average of the values in the array.

 

Finishing Up

 

Homework J6

Use any remaining time in the lab to work on HW J6.