Skip to content
UoL CS Notes

Arrays

COMP122 Lectures

Arrays are variable storing fixed-length lists of values with the same type.

For example we can have an integer array called count and type int[].

Array Types

For every type x there is a corresponding array type x[].

Declaring Array Variables

int[] numbers;
double[] reals;
boolean[] truthValues;

Creating Arrays

In order to use an array variable, the compiler needs to know the length of the array to allocate the appropriate chunk of memory.

There is a special statement that creates a new array:

double[] rates = new double[200];
boolean[] truthValues = new boolean[18];

// Length defined by another variable
int alphabetSize = 26;
int[] count = new int[alphabetSize];

Remarks on Arrays

  • Every array has a length attribute which tells you its size:

      int sizeOfAlphabet = count.length;
    
  • Array elements are accessed by index using square brackets:

      numberOfAs = count[0];
      numberOfCs = count[2];
    

Multi-dimensional Arrays

Every type x has an associated type x[]. This includes arrays. For example we can represent a chess board as 2D integer arrays.

int[][] board = new int [8][8];

You can also define arrays literally:

int[][] board = {
	{0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0},
	...
	{0,0,0,0,0,0,0,0}
}