Arrays

Standard data structures in Java

An array in Java is a way to store large amounts of data more easily. For example, If we had the marks of 20 students and had to create a variable for each mark, we would do

int mark1 = 80;

int mark2 = 92;

int mark3 = 77;

int mark4 = 96; ...


(etc.)

Having to create a single variable for each mark would be too tedious and hard to use as well. To fix this problem, we can use an array. An array is a block of memory in Java that can be used to store multiple elements, similar to a list (shopping list or to-do list). An array can be created with a set length, and elements stored in the array will have their own index in the array. For example, if we wanted to create an array that could store 20 student test marks, we can do

int testMarks[] = new int[20];

Then, we can access and assign elements to this array:

testMarks[0] = 80;

testMarks[1] = 92;

System.out.println(testMarks[0]);


or use a for loop to initialize the array:

for (int i = 0; i < testMarks.length; i++) {

testMarks[i] = nextMark();

}

Some important rules to remember when using arrays:

  • The length of arrays cannot be changed once initialized

  • The index of arrays go from 0 to array.length-1 ; they do NOT start from 1.

  • Do not access negative indices or indices outside the array's bounds. Doing so will cause an ArrayIndexOutOfBoundsException

Two Dimensional Arrays

2D arrays can be made by creating an array full of arrays. This makes it so that programmers can make grids, matrices, or tables. A two-dimensional array can be made by typing

Type nameOfArray[][] = new Type[numRows][numCols];

For example, a two-dimensional integer array called "table" with 5 rows and 9 columns would be created as

int table[][] = new int[5][9];

Just like a 1D array, 2D arrays can have object types as well. An index of a two-dimensional array can be accessed by typing

nameOfArray[rowIndex][colIndex]

For example, setting a value in the table example would be done by typing

table[1][3] = 25;

And getting a value in the table and printing it to the screen would look like

System.out.println(table[2][4]);


Remember that indices of two-dimensional arrays start from 0 and end at length-1 just like 1D arrays.

Traversing a 2D array can be done using a nested for-loop or while-loop, such as

for (int row = 0; row < table.length; row++) {

for (int col = 0; col < table[row].length; col++) {

System.out.println(table[row][col]);

}

}