INF 208 Programming - Java: Arrays
INF 208 Programming - Java: Arrays
Arrays
Arrays
array: object that stores many values of the same
type.
• element: One value in an array.
• index: A 0-based integer to access an element from an array.
index 0 1 2 3 4 5 6 7 8 9
value 12 49 -2 26 5 17 -6 84 72 3
System.out.println(numbers[0]);
if (numbers[3] < 0) {
System.out.println("Element 3 is negative");
}
index 0 1 2 3 4 5 6 7 8 9
value 27
0 0 0 -6
0 0 0 0 0 0 0
Arrays of other types
double[] results = new double[5];
results[2] = 3.4;
results[4] = -0.5;
index 0 1 2 3 4
value 0.0 0.0 3.4 0.0 -0.5
index 0 1 2 3 4 5
value false false false true false false
Out-of-bounds
value 0 0 0 0 0 0 0 0 0 0
Accessing array elements
index 0 1 2 3 4 5 6 7 8 9
value 0 3 11 42 99 0 2 0 0 0
numbers
Arrays and for loops
It is common to use for loops to access array
elements.
for (int i = 0; i < 8; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();// output: 0 4 11 0 44 0 0 2
index 0 1 2 3 4 5 6 7
value 0 2 4 6 8 10 12 14
The length field
a1 index 0 1 2 3 4 5 6
value 7
4 5 2 12 14 14 9
a2
Arrays as parameters
Declaration:
public static type methodName(type[] name) {
Example:
public static double average(int[] numbers)
{
Call:
methodName(arrayName);
Example:
int[] scores = {13, 17, 12, 15, 11};
double avg = average(scores);
Array parameter example
Output:
Average = 124.2
Arrays passed by reference
• Example:
• Example:
Output:
[2, 1, 3, 1, 0, 0, 0, 1, 0, 1]
Reading: 7.1-7.4
Self-Check Problems pg 505: 1-11, 13-17
Exercises pg 511: 1-4