Declaring Methods  «Prev 


Java Array Dimensions

Technically, Java does not have multidimensional arrays. Multidimensional arrays are arrays of arrays. In practice, this technicality doesn't mean much. However, you should note that it is possible to have an array of arrays in which the array elements are of different sizes. The following array declaration illustrates this point. It declares oddArray as an array of different size arrays.

               
int[][] oddArray = {{1},{2,3},{4,5,6}};

What is an array?

An array is an object that stores a collection of values. The fact that an array itself is an object is often overlooked. I will reiterate, "an array is an object itself", which implies that it stores references to the data it stores. Arrays can store two types of data:
  1. A collection of primitive data types
  2. A collection of objects
An array of primitives stores a collection of values that constitute the primitive values themselves. (With primitives, there are no objects to reference.) An array of objects stores a collection of values, which are in fact heap-memory addresses or pointers. The addresses point to (reference) the object instances that your array is said to store, which means that object arrays store references (to objects) and primitive arrays store primitive values. The members of an array are defined in contiguous (continuous) memory locations and hence offer improved access speed. (You should be able to quickly access all the students of a class if they all can be found next to each other.)


Note: Arrays are objects and refer to a collection of primitive data types or other objects.
In Java, you can define one-dimensional and multidimensional arrays. A one-dimensional array is an object that refers to a collection of scalar values. A two-dimensional (or more) array is referred to as a multidimensional array. A two-dimensional array refers to a collection of objects in which each of the objects is a one-dimensional array. Similarly, a three-dimensional array refers to a collection of two-dimensional arrays, and so on. Figure 4-3 depicts a one-dimensional array and multidimensional arrays (twodimensional and three-dimensional).
Note that multidimensional arrays may or may not contain the same number of elements in each row or column, as shown in the two-dimensional array in figure 4-3. Creating an array involves three steps, as follows:
  1. Declaring the array
  2. Allocating the array
  3. Initializing the array elements
Array Elements
Figure 4-3: One-dimensional and multidimensional (two- and three-dimensional) arrays

Multidimensional Arrays

The following array arr[i][j][k] is simply an array, of arrays, of arrays.
If you know how arrays work, you know how multidimensional arrays work.

int[][][] threeDimArr = new int[4][5][6];

or, with initialization:
int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };