Chapter 13



Array Notes

Dr. Leah Cook

updated: Dec. 2, 2003

Array

An array is a data structure, similar to a table, in which all of the components have the same data type. Arrays can have one-dimension (single column or row) or many dimensions. The data type of an array can be primitive (int, boolean, double) or can be an object (String, Color, etc.). When an Array is instantiated, a block of computer storage is reserved with the number of components requested. Each individual component of an Array (also known as an element) has the array name and an index (or subscript) that identifies the specific component. Array indices are numbered starting with zero.

“John” “Paul” “George” “Ringo” An array of Strings

0 1 2 3 Indices

Declaring an Array (under the class header)

syntax: datatype[ ] name;

String[] beatles;

int[] scores;

Instantiating an Array (init() method)

syntax: array name = new datatype [number of components]

beatles = new String[4];

scores = new int[10];

Declaring And Instantiating in one Step

private String[] beatles = new String[4];

private int[] scores = new int[10];

Array indices / input / output/ assignment

Array components are referred to by the array’s name and an index within square brackets.

beatles[1] = “Paul”;

beatles[2] = nameField.getText();

score[5] = Integer.parseInt(scoreField.getText());

System.out.println(beatles[3]);

score[v] = 88; // v is a variable

score[j] = score[j-1] + score[j+1]; // j is a variable

Looping across Arrays / length property

Arrays are used with loops. The length property returns the number of components in an array and is used to loop across an array.

for (int i = 0 ;i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download