Two Dimensional Arrays

Creating Two Dimensional Arrays

🙋 Need help? Ask an expert now!

Let's expand our array conversation to two-dimensional arrays. Spreadsheets, web browser screens, images, and many other types of data are in a 2D format, which is why we need arrays that can handle this type of data. A 2D array is laid out in a grid like graph paper, meaning each element is still housed in its own cell like in a 1D array. However, that element is now represented by two different indexes that are both needed in order to specify that cell. Take a look at the 2D arrays below.
package exlcode;

public class TwoDimensionalArraysExample {

  public static int[][] exampleVariableOne = new int[3][4];
  public static int[][] exampleVariableTwo = {{0, 1, 2, 3, 4}, {4, 5, 6, 7, 8}};
  public static boolean[][] exampleVariableThree = {{true, false, false, true}, {false, false, true, true}};

  public static void main(String[] args) {
    exampleVariableOne[1][2] = 10000;
    // the default value for int[][] elements when declared is also 0

Similar to 1D arrays, the index of both row and column start at 0. The first square bracket after the array name specifies the row while the second one dictates the column. All indexes start at 0, so varOne[0][0] specifies the first row and the first column. If you have varOne[3][1], you are indicating the element that exists in the fourth row and the second column. Like 1D arrays, all the elements must have the same datatype. Initializing a 2D array is also very similar to initializing a 1D array.

  1. datatype[][] arrayname = new datatype[3][1];

Creates a 2D array with three rows and one column.

  1. datatype[] arrayname = {{varOne, varTwo}, {varThree, varFour}};

Creates a 2D array with two rows and two columns. The rows are separated by commas and enclosed in individual curly braces.

Application Question

Which of the following statements assigns the letter 'A' to the 3rd row and 1st column of the two-dimensional array?
Note that there is no "0th column" or "0th row".