2D Array

Java also supports the use of two-dimensional (“D) arrays, or even multidimensional arrays. A multidimensional array is declared by using two or more sets of square brackets, such as String[][] names. Each element must be accessed by a corresponding number of index values, so for a 2D array you would need 2 index values, for a 3D array you would need 3 and so on.

In Java a multidimensional array is an array of arrays. This is unlike arrays in other programming languages like C or Fortran. This means that the rows in an array can vary in length, as shown in the MultiDim ArrayDemo program from The Java Tutorials:

package multidimarraydemo;

public class MultiDimArrayDemo {

    public static void main(String[] args){
        String[][] names = {
            {"Mr. ","Mrs. ","Ms. "},
            {"Smith","Jones"}};

        // Mr. Smith
        System.out.println(names[0][0] +
                           names[1][0]);
        // Ms. Jones
        System.out.println(names[0][2] +
                           names[1][1]);
    }
}

The output from this program is:

Mr. Smith
Ms. Jones

The built-in length property can be used to determine the size of an array. The following code prints the array’s size to standard output:

System.out.println(anArray.length);

Next: Hash Table