This is an example of two-dimensional arrays in java. 2D arrays are just arrays of arrays.

public class TwoDArray {
    public static void main(String [] args) {
	int [][] arr1 = { {1, 2, 3}, {4, 5, 6} }; // 2-by-3 array
	int [][] arr2 = new int[3][2]; // memory for a new 3-by-2 array

	// initializing some elements of the new array
	// the rest of elements are zeros
	arr2[0][1] = 7;
	arr2[1][0] = 8;
	arr2[2][1] = 9;

	// priniting the first array
	for (int i = 0; i < arr1.length; i++) {
	    for (int j = 0; j < arr1[i].length; ++j) {
		System.out.println("a[" + i + "," + j + "] = " + arr1[i][j]);
	    }
	    System.out.println();
	}

	// printing out the second array
	for (int i = 0; i < arr2.length; i++) {
	    for (int j = 0; j < arr2[i].length; ++j) {
		System.out.println("a[" + i + "," + j + "] = " + arr2[i][j]);
	    }
	    System.out.println();
	}
    }
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.