Chapter 6
Outline
• Array Basics
• Arrays in Classes and Methods
• Sorting Arrays
• Multidimensional Arrays
Introduction to Arrays
• An array is an object used to store a (possibly
large) collection of data.
• All the data stored in the array must be of the
same type.
• An array object has a small number of
predefined methods.
Introduction to Arrays, cont.
• Sometimes you want to know several things
about a collection of data:
– the average
– the number of items below the average
– the number of items above the average
– etc.
• This requires all the items to be stored as
variables of one kind or another.
Introduction to Arrays, cont.
• example
double[] temperature = new double[7];
is like declaring seven variables of type
double, named
temperature[0], temperature[1],
temperature[2], temperature[3],
temperature[4], temperature[5], temperature[6].
Creating and Accessing
Arrays, cont.
• These variables can be used just like any
other variables of type double.
• examples
temperature[3] = 32.0;
temperature[6] = temperature[3] + 5;
System.out.println(temperature[6]);
temperature[index+1] = 66.5;
• example
int[] pressure = new int[100];
or
int[] pressure;
pressure = new int[100];
Array Details, cont.
• The type of the elements is called the base
type.
• The base type of an array can be any type
including a class type.
– for example,
Species[] entry = new Species[3];
• example
for (lcv = 0; lcv < temperature.length;
index++)
Array Index Out of Bounds
• Every index must evaluate to an integer
which is not less than 0 and not greater than
Array_Name.length-1.
or
int[][] table;
table = new int[10][6];