Arrays in Java

An array contains a collection of elements, all of which have the same type. Arrays can be of any type. An array declaration is of the form

datatype variable_name [] ;

or

datatype [] variable_name;


We have already seen an array, args, of type String in the Circle program. If we wish to declare an array, intArray, say, of type int, enter either

int [] intArray;

or

int intArray[];


This statement only declares the variable intArray. To create or define an array, that is, reserve storage in memory to hold the array, we need to use the new keyword. For example,

intArray = new int [2];

will create the array intArray with two elements and initialize it with zero values, the default value for numbers. The reason for the new keyword is that an array is actually an object in Java. Objects in Java are created using the new keyword, as we shall see in Chapter 4.

Array elements are counted from zero, so


intArray[0] = 1;

assigns the value of 1 to the first element of intArray. Note that once an array is created, its size cannot be changed.

An example of all this is the OutputArray program, which assigns the values of 1 and 2 to an integer array and outputs the results.


OutputArray


One can declare, create, and assign initial values to an array in a single statement, so we can replace lines 4–7 with the statement

int intArray[] = {1,2};

Arrays of arrays can be constructed in Java, by using consecutive pairs of brackets: [][]. OutputTable populates a two-dimensional array or table of type int.

public class OutputTable {
public static void main(String[] args) {
int table [] [] = {
{1, 2},
{3, 4, 5}
};
System.out.println("Values of table are "

+ table[0][0] + '' , " + table[0][1] + " , "
+ table[1][0] + " , " + table[1][1] + " , "
+ table[1][2]);
}
}




The main array, table, consists of two subarrays, table [0] and table [1]. Note the subarrays can be of different lengths. We could have defined the table array as

int table [] [] = new int [2] [3];

and populated the array element by element. To find the length of an array, use

array_name.length

So in our table array example,table.length returns the value 2, and table[1].length returns the value 3.


The reason we can have arrays of arrays is that an array, like all objects, is a reference type. This means that the memory address is stored in an array variable. The value of the variable is a reference to a value or, indeed, to another array. So table[1][2] is a reference to the value 5, while table[0] is a reference to the array with elements table[0][0] and table[0][1].Following figure 2.1 shows how the two-dimensional table array is implemented.

No comments:

Post a Comment