Home » Java Basics » 03 - Java Installation and Simple Programs
3

Basic Java Objects - Arrays

Specific number of values of the same type

While variables hold single values, arrays hold a specific number of values of the same type. Each value in an array is called an element and may be retrieved using its numerical index. The index is a number that ranges from 0 to one less than the total number of elements in the array (also known as the length or size of the array). For example, the first element in an array named myArray may be accessed using the index 0 as follows: myArray[0]. The last element in the array may be accessed through myArray[n-1] where n is the total number of elements in the array. Arrays may be declared and set in the following manner:

String[]  stringArray;  //A string array declaration
stringArray = new String[10];  //Memory is allocated for ten elements
stringArray[0] = "ABC"
stringArray[1] = "DEF"
stringArray[2] = "GHI"
stringArray[3] = "JKL"
stringArray[4] = "MNO"
stringArray[5] = "PQR"
stringArray[6] = "STU"
stringArray[7] = "VWX"

Alternatively, an array may also be initialized in the following way

String[]  stringArray;  //A string array declaration
stringArray = { "ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VWX"}

Arrays of Arrays, or multidimensional arrays, may be declared as follows:

int[][] twoDimArray;

Such an array would have a total of (m x n) elements where ‘m’ is the size of the first dimension and ‘n’ is the length of the second dimension. However, since Java represents each element of the first dimension of a multidimensional array as an array containing the other dimensions rather than as a cell in a matrix or table, the length of the second dimension may vary.

int[][] twoDimArray;
twoDimArray = {{1,2,3},{1,2,3,4,5},{1,2,3,4},{1},{1,2});

The main curly braces enclose the first dimension separated by commas; the inner curly braces hold the elements of the second dimension. The first dimension of the above array has a length of 5; the length of the second dimension varies from 1 to 5. The System class that we used to print out the line "Hello World" on the screen has an arraycopy method (a static method invoked by the classname) that copies data from one array to another. This method may be used to set arrays of similar type equal to another.