Free Java Tutorials >> Table of contents >> Two Dimensional Arrays

1. 2D arrays

Two dimensional Arrays

While the one dimensional array such as int[] can be represented as a line, a two dimensional array int[][] can be visualized as a grid. Usually, we refer to the first dimension as "rows" (the y axis) and the second dimension as columns (the x axis). This is how we create a two dimensional array:

public class MyProgram {
    public static void main(String[] args) {
		int[][] x = { {10,20},{30,40},{50,60} };
		//When drawn on a piece of paper, this looks like:
		//10 20
		//30 40
		//50 60

		int[][] y = { {1},{2,3},{4,5,6} }; //notice that the subarrays can be of different lengths.
		//y looks like:
		//1
		//2 3
		//4 5 6

		int[][] z = new int[2][4];  //All values are by default zero in this initialization
		//z looks liks:
		//0 0 0 0
		//0 0 0 0
    }
}

Indexing into two dimensional arrays

To get the first row and third column of an array int[][] nums, we type nums[0][2]. We can also set the value here with nums[0][2] = 5. Additionally, these indices can be replaced with variables of type int. Thus, we can build this example that prints a two dimensional array:

public class MyProgram {
    public static void main(String[] args) {
		int[][] wat = { {10},{20,30},{40,50,60} };
		for(int j = 0; j < wat.length ; j++) {    //j is less than the # of ROWS (wat.length)
			for(int i = 0; i < wat[j].length; i++) {//i is less than the # of COLUMNS (wat[j].length)
				//note that because this is an irregular array
				//the number of columns changes depending on the row
				System.out.print(wat[j][i]); //print, unlike println, does not add a new line when run
				System.out.print(" "); //adds a space between columns
			}
			System.out.println("");  //adds a new line between rows
		}
	}
}

Once we have this two dimensional loop, we can extend one dimensional algorithms to two dimensions. By placing an if statement in the inner most loop as well as two index variables, we can search for an item, locate the position of a maximum, locate the position of a minimum, and more. We can also sum up a two dimensional array by adding a sum variable before the loop. Other algorithms, such as matrix addition (adding one two dimensional array to another) may interact with two equally sized grids using the same two loops. All use these loops

2. Jagged Arrays

Modifying the second dimension (columns)

As we saw, a 2d array can have a different number of columns per row. We can actually declare 2d arrays with 0 columns per row:

public class MyProgram {
    public static void main(String[] args) {
		int[][] x = new int[5][]; //5 rows, 0 columns
		//Advanced students should note that here
		//each subarray is actually null
		
		//Advanced students should note that the
		//subarrays here are (new int[0]):
		int[][] y = { {},{},{} }; //3 rows, 0 columns

		int[][] z = new int[4][0];//4 rows, 0 columns
    }
}

Then, we can assign each row to equal an array:

public class MyProgram {
    public static void main(String[] args) {
		String[][] x = new String[3][]; //3 rows, 0 columns
		x[0] = new String[]{"One"};
		x[1] = new String[]{"Two","Words"};
		x[2] = new String[]{"Three","Whole","Words"};
		
		for(int j = 0; j < x.length ; j++) {    //j is less than the # of ROWS (x.length)
			for(int i = 0; i < x[j].length; i++) {//i is less than the # of COLUMNS (x[j].length)
				System.out.print(x[j][i]); 
				System.out.print(","); 
			}
			System.out.println("");  //adds a new line between rows
		}
    }
}

3. Matrix Sum

What is a matrix?

The mathematical term matrix usually means a rectangular two dimensional array. In other words, each row has the same number of columns. We can add two matrices if they have the same number of rows and columns:

public class MyProgram {
    public static void main(String[] args) {
		int[][] x = { {10,20},{30,40},{50,60} };
		int[][] y = { { 1, 2},{ 3, 4},{ 5, 6} };
		
		//declare sum to be the same number of
		//rows and columns as x
		int numrows = x.length;
		int numcols = x[0].length;
		int[][] sum = new int[numrows][numcols];
		
		for(int j = 0; j < numrows ; j++) {   
			for(int i = 0; i < numcols; i++) {
				sum[j][i] = x[j][i]+y[j][i];
			}
		}
		
		//Now let's print sum:
		for(int j = 0; j < sum.length ; j++) { 
			for(int i = 0; i < sum[j].length; i++) {
				System.out.print(sum[j][i]); 
				System.out.print(" "); 
			}
			System.out.println("");  
		}
		//Output:
		//11 22 
		//33 44 
		//55 66 
    }
}

Previous: Array Algorithms

Next: Advanced Array Algorithms