Table of ContentsStringsAdvanced Object-Oriented Programming

Arrays

An array variable can store multiple variables in a single element. It can contain any type of variable, including objects, but this type must be the same for all elements.

To declare an array type, use the general variable declaration with the array operator either before or after the identifier name. For example, both of these declarations are for an array of integers:

int a[];
int[] a;

Before you can use an array variable, you have to initialize it using a list of expressions enclosed in braces. For example:

int[] a = { 10, 20, 30, 40 };

This code creates an integer array of four elements with the integer values 10 through 40. To access one of these elements, you use the array index operator:

int b = a[3];  // b is equal to 40

You should keep in mind that array access starts at zero, so the first entry in the array is at [0] and the last is at the array's length minus one.

To determine the size of an array, you can use a special property available with any array variablelength.Here's an example. (Note that this is not a method call.)

System.out.println(a.length);  // output is "4"

Arrays can also have more than one dimension. Here's the same example code expanded to an extra dimension:

int[][] a = { { 10, 20, 30, 40 }, { 50, 60, 70, 80 } };
int b = a[0][0];    // b is equal to 10
int b = a[1][3];  // b is equal to 80

    Table of ContentsStringsAdvanced Object-Oriented Programming