zuai-logo

2D Arrays

Emily Wilson

Emily Wilson

6 min read

Listen to this study note

Study Guide Overview

This study guide covers 2D arrays in Java, including initializing empty and pre-existing arrays (both rectangular and non-rectangular). It explains memory representation as nested arrays and graphical representation as grids/tables. The guide also details accessing elements using double-index notation (row, column), potential ArrayIndexOutOfBoundsExceptions, and provides practice questions using these concepts.

Initializing 2D Arrays

We can declare and initialize a 2D array in much the same form as a regular array, but with some subtle differences. There are still two ways to do so.

Initialize an Empty 2D Array

We can initialize an empty 2D array that fills the array with the same "null"/initialized values as when we use the regular arrays from Unit 6 (also called 1D arrays). However, this only works for "rectangular" arrays, where the two dimensions are clearly defined. We will talk more about this in the next subsection. Here is how to do this:

/* Template: type[][] twoDArrayName = new type[firstDimension][secondDimension] */ int[][] arrayA = new int[3][4];

Initialize a Pre-existing 2D Array

You can also initialize this with a pre-existing 2D array. This is similar to how you do 1D arrays.

Here is an example of an int[3][4] 2D array but with values pre-initialized:

int[][] arrayB = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

You don't have to use integers for the type stored in the array. You can use any other primitive or reference type! Integers are only used in this guide for simplicity.

Representing 2D Arrays

The 2D arrays can be represented in 2 major ways: one that is more...

Question 1 of 10

What is the correct syntax to declare an empty 2D integer array named 'grid' with 3 rows and 5 columns? 🚀

int[][] grid = new int[5][3];

int grid[][] = new int[3, 5];

int[][] grid = new int[3][5];

int[3][5] grid = new int[][];