Skip to main content

more options

Arrays in Java

Introduction

Java, like most programming languages has arrays —lists of elements of a certain type, where the size of a list is fixed when the array is first created. In Java, arrays are objects.

We provide a very brief summary of one- and two-dimensional arrays. Turn to Chapter 8, pp. 271–297, of Gries/Gries for complete discussion of one-dimensional arrays. Read Chapter 9, pp. 301–311 to see how a two-dimensional array is handled as an array of arrays.

Declaration of one-dimensional array variables

Use

int[] b;
JFrame[] j;

to declare a variable b that can contain an object that is an array of ints and a variable j that can contain an object that is an array of JFrames. Arrays are objects, and variables b and j can contain the names of array objects. Initially, b and j contain null.

Note that int[] and JFrame[] are types. We read these as type "int array" and type "JFrame array".

Creation of an array

Evaluation of the new-expression

new <type> [ <integer-expression> ]

creates an array that contains <integer-expression> elements, all of type <type>. So, below we create an array of 10 ints and an array of 20 JFrames and store them in b and j:

b= new int[10];       // Initally, each array element contains 0.
j=
new JFrame[20];   // Initially each array element contains null.

The number of elements in the arrays are given by b.length and j.length.

Referencing and changing array elements

Array indexing starts at 0; e.g. the elements of array b are referenced using b[0], b[1], ..., b[b.length-1]. The following assignment adds 1 to b[k]:

b[k]= b[k] + 1;

and the following procedure call sets the title of j[3]:

j[3].setTitle("Element number 3");

Two-dimensional arrays

A two-dimensional int array has type int[][]. So, to declare an array variable of this type, use:

int[][] c;

To create a two-dimensional 20-row by 30-column int array and store it (i.e. its name) in c, write:

c= new int[20][30];

The number of rows, 20, is given by c.length; the number of columns in row 3 by c[3].length.

To add 1 to the array element in row 3 column 5 of c, write:

c[3][5]= c[3][5] + 1;