2D Arrays

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...

How are we doing?
Give us your feedback and let us know how we can improve