[course08] 01 One-dimensional array

[course08] 01 One-dimensional array

A one-dimensional array is a data structure used to implement a list object, where the elements in the list are of the same type.

For an array of N elements in Java, index values (“subscripts”) go from 0 to N − 1. Individual elements are accessed as follows: If arr is the name of the array, the elements are arr[0], arr[1], ..., arr[N-1]. If a negative subscript is used, or a subscript k where k ≥ N, an ArrayIndexOutOfBoundsException is thrown.

Initialization


double[] data = new double[25];
double data[] = new double[25];
double[] data; 
data = new double[25];

int[] intList1, intList2;
int[] arr1 = neZ int[15], arr2 = neZ int[30];

initialization list

int[] coins = neZ int[4];
coins[0] = 1;
coins[1] = 5;
coins[2] = 10;
coins[3] = 25;

int[] coins = {1, 5, 10, 25};

Length of array

  1. The array subscripts go from 0 to names.length-1; therefore, the test on i in the for loop must be strictly less than names.length.

  2. length is not a method and therefore is not followed by parentheses. Contrast this with String objects, where length is a method and must be followed by parentheses.

Traversing a One-dimensional array

Arrays as Parameters

Since arrays are treated as objects, passing an array as a parameter means passing its object reference. No copy is made of the array. Thus, the elements of the actual array can be accessed—and modified.

example 2

When an array is passed as a parameter, it is possible to alter the contents of the array.

example 3

example 4

example 5

Array variables in a class

Array of Class Objects

Last updated

Was this helpful?