5 min read•Last Updated on June 18, 2024
Avanish Gupta
Avanish Gupta
2D Arrays: 2D Arrays can be used to organize data into a grid, and with the appropriate methods, we can access and manipulate this data.
In the past two units, you've learned how to store data in an array or an ArrayList. Now it's time to take it to another dimension with 2D arrays. You can either think of them as a grid or as a nested array, and we'll use both methods of thinking in this unit. Using these, we'll learn how to set these up and also how to traverse them.
For this unit, we will first learn how to create and initialize 2D arrays with various types of objects. These will be nested arrays. When traversing a list, you need to use nested arrays for loops, and these will need to have proper bounds to avoid an ArrayIndexOutOfBoundsException. If you can master 2D arrays, you can easily do 3D and higher-dimensional arrays if you ever decide to continue using Java after this course!
We can declare and initialize a 2D array in much the same form as a regular array, but with some subtle differences. However, there are still two ways to do so. 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];
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.
The 2D arrays can be represented in 2 major ways: one that is more visual, and one that is closer to how it is stored in the memory.
The first way to think about this is how it is stored in memory, or in terms of data structures. A 2D array in this form is just a nested array. There is an outer array having arrays for its individual terms. In each inner array, the terms are objects or primitive type values of the type stated during initialization. When we initialize an array of type[firstDimension][secondDimension], we are actually initializing an array of length firstDimension (remember to use length instead of size as size is only for ArrayLists as in Unit 7). Each item in this array is another array containing secondDimension items of the specified type. For example, arrayA is an array with 3 items, each of which is an array with 4 integers.
A 2D array does not have to be rectangular. The inner arrays can vary in size. Here is an example of a non-rectangular array:
int[][] arrayC = {{1, 2}, {3}, {4, 5, 6}};
However, for the rest of this unit, we will be concerned with rectangular arrays, as those will be the type tested on the AP Exam.
For rectangular arrays, we can think of these as a grid, table, or matrix (if you have learned them in a prior math class). We can express arrayB from earlier as follows:
int[][] arrayB = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
For a 2D array, type [firstDimension][secondDimension] . In this representation, firstDimension is the number of rows and secondDimension is the number of columns. Remember that arrayB is an example of an int[3][4] 2D array. Using the same logic, arrayB has 3 rows and 4 columns.
From this visual idea, we can easily find the indices to access an individual element of a 2D array.
[0][0] | [0][1] | [0][2] | [0][3] |
[1][0] | [1][1] | [1][2] | [1][3] |
[2][0] | [2][1] | [2][2] | [2][3] |
For indices, we use 2 bracketed numbers, called double-index notation, with the first being the row and the second being the column. Remember that Java is a 0-indexed language, so the row indices range from [0, 1, 2, ..., firstDimension - 1] and the column indices range from [0, 1, 2, ..., firstDimension - 1].
For a pre-initialized array, the number of rows is the length of the outer array, which is arrayName.length, while the number of columns is the length of each inner array, which for rectangular arrays is arrayName[0].length.
With double-index notation, we can access any element of the array. However, if you use an index that is not in the allowed range, you get an ArrayIndexOutOfBoundsException. For example, for arrayB, saying arrayB[2][3] means that we want the element in the third row and the fourth column, which corresponds to 12. Lets do a little practice using arrayB from above:
What are the indices for the following:
We will use the graphical representation of 2D arrays in the rest of this unit as it is easier to visualize and understand.
A 0-indexed language is a programming language where arrays and other data structures start counting from 0 instead of 1. In these languages, the first element is accessed with an index of 0.
Term 1 of 29
A 0-indexed language is a programming language where arrays and other data structures start counting from 0 instead of 1. In these languages, the first element is accessed with an index of 0.
Term 1 of 29
A 0-indexed language is a programming language where arrays and other data structures start counting from 0 instead of 1. In these languages, the first element is accessed with an index of 0.
Term 1 of 29
2D arrays are data structures that store values in a grid-like format with rows and columns. They allow for the organization and manipulation of data in a two-dimensional manner.
Methods: In programming, methods are blocks of code that perform specific tasks. They can be used to manipulate or retrieve data from 2D arrays.
Access: Access refers to the ability to retrieve or modify the values stored in an array. In the context of 2D arrays, it involves accessing specific elements using their row and column indices.
Arrays: Arrays are data structures that store multiple values of the same type. A 2D array is simply an extension of this concept, allowing for storage in a grid-like format instead of just linearly.
A grid is a two-dimensional arrangement of cells or elements organized in rows and columns.
Table: A table is similar to a grid, but it is typically used to organize data in a structured manner, with rows representing records and columns representing attributes.
Matrix: A matrix is also a type of grid, but it specifically refers to a rectangular array of numbers or elements arranged in rows and columns.
Array: An array is another term for a grid-like structure that stores multiple values of the same data type consecutively in memory. It can have one or more dimensions.
Manipulate refers to the process of changing or altering data in a program. It involves modifying variables, arrays, or objects to achieve a desired outcome.
Variable: A variable is a named storage location in a program that holds a value. It can be manipulated by assigning new values to it.
Array: An array is a collection of elements of the same type stored in contiguous memory locations. It can be manipulated by accessing and modifying individual elements.
Object: An object is an instance of a class that encapsulates both data (attributes) and behavior (methods). It can be manipulated by invoking its methods or accessing/modifying its attributes.
Multiple-choice questions are a type of assessment where students choose the correct answer from a set of options. Each question typically has one correct answer and several distractors.
Distractors: These are incorrect options in multiple-choice questions that aim to confuse or mislead students.
Stem: The stem is the main part of a multiple-choice question that presents the problem or asks for information.
Answer Key: An answer key provides the correct answers for multiple-choice questions, allowing students to check their responses against it.
FRQ #4 refers to the fourth free-response question in the AP Computer Science A exam. It is a coding problem that requires students to write a program to solve a specific task or problem.
Free-response question (FRQ): These are questions in the AP Computer Science A exam where students have to write code or explain concepts in detail.
Coding problem: A task or challenge that requires writing code to solve it.
Algorithm design: The process of creating step-by-step instructions for solving a specific problem using programming.
An array is a fixed-size collection of elements of the same type stored in contiguous memory locations. It allows efficient access to individual elements using an index.
Indexing: Indexing refers to accessing individual elements within an array by specifying their position using an index value.
Length/Size: The length or size represents the total number of elements present in an array.
Multidimensional Array: A multidimensional array is an array with multiple dimensions (rows and columns) that allows storing data in tabular form.
ArrayList is a dynamic data structure that allows you to store and manipulate collections of objects. Unlike arrays, ArrayLists can grow or shrink dynamically as needed.
List Interface: A Java interface that defines common methods for working with lists.
add(): A method used to insert elements into an ArrayList.
remove(): A method used to delete elements from an ArrayList.
A nested array is an array that contains other arrays as its elements. It allows for the creation of multi-dimensional data structures.
Multi-dimensional Array: A multi-dimensional array is similar to a nested array, but it can have more than two dimensions. It allows for the organization of data in multiple levels or layers.
Indexing: Indexing refers to accessing specific elements within an array by using their position or index number.
Jagged Array: A jagged array is an irregularly shaped multidimensional array where each row can have a different length. It provides flexibility when dealing with varying amounts of data in different rows.
Initializing 2D arrays means setting up or creating a two-dimensional array with initial values before using it in a program.
Array Declaration: Array declaration refers to specifying the type and size of an array before using it in a program.
Array Initialization: Array initialization involves assigning initial values to individual elements of an array during its creation.
Two-Dimensional Array: A two-dimensional array is an organized collection of data elements arranged in rows and columns. It allows for storing and accessing data in a tabular format.
ArrayIndexOutOfBoundsException is an exception that occurs when trying to access an invalid index position in an array. It is thrown to indicate that the index used to access an array is either negative or greater than or equal to the size of the array.
Exception handling: The process of dealing with and responding to exceptional situations or errors that occur during program execution.
Bounds checking: The practice of verifying whether an index value falls within the valid range of indices before accessing elements in an array.
Runtime error: An error that occurs during program execution rather than during compilation.
Initializing 2D arrays refers to the process of declaring and assigning values to a two-dimensional array. It involves specifying the size of the array and providing initial values for each element.
Declare and Initialize: This term refers to the process of creating and assigning an initial value to any variable or data structure.
2D Array: A two-dimensional array is an organized collection of elements arranged in rows and columns, forming a grid-like structure.
Rectangular Arrays: Rectangular arrays are another term used to describe two-dimensional arrays because they have rows and columns that form a rectangular shape.
Representations of 2D arrays refer to different ways in which two-dimensional arrays can be visualized or stored in memory. There are multiple representations available, such as using nested loops, using matrices, or using lists of lists.
Nested Loops: A programming construct that involves using one loop inside another loop to iterate through a two-dimensional array.
Matrices: A mathematical representation of a two-dimensional array using rows and columns.
Lists of Lists: A data structure where each element is itself a list, allowing for the creation of nested lists to represent a two-dimensional array.
Traversing 2D arrays refers to the process of accessing and examining each element in a two-dimensional array. It involves iterating through the rows and columns of the array to perform operations on each element.
Accessing Elements: Refers to retrieving or modifying specific elements within a data structure like an array.
Nested Loops: A programming construct that involves using one loop inside another loop, commonly used for traversing multi-dimensional arrays.
Row-major Order: A method of storing elements in a 2D array where consecutive elements are stored row by row.
An outer array is an array that contains other arrays as its elements.
Inner Array: An inner array refers to an array that is contained within another array.
Multidimensional Array: A multidimensional array is an array that contains arrays as its elements, forming a matrix-like structure.
Nested Arrays: Nested arrays are arrays that are placed inside other arrays, creating a hierarchical structure.
An inner array refers to an array that is contained within another array.
Outer Array: An outer array is an array that contains other arrays as its elements.
Multidimensional Array: A multidimensional array is an array that contains arrays as its elements, forming a matrix-like structure.
Nested Arrays: Nested arrays are arrays that are placed inside other arrays, creating a hierarchical structure.
Primitive type values refer to basic data types in programming languages such as integers, floating-point numbers, characters, booleans, etc., which are not composed of smaller parts.
Reference Type Values: Reference type values refer to objects or instances created from classes in object-oriented programming languages.
Data Types: Data types define the kind of values that can be stored and manipulated in a programming language.
Variables: Variables are named storage locations used to hold values of specific data types during program execution.
The length refers to the number of elements in an array or the size of a string.
Index: It is the position of an element within an array or a character within a string.
Size: It represents the total amount of memory allocated to store data, which can be different from the length if there is unused space.
Capacity: It refers to the maximum number of elements that an array can hold, which may be greater than its current length.
A non-rectangular array is an array where each row can have a different number of columns.
Jagged Array: It is another term used to describe non-rectangular arrays because their rows have varying lengths, resembling jagged edges.
Two-dimensional Array: Unlike non-rectangular arrays, two-dimensional arrays have fixed dimensions with equal numbers of rows and columns.
Nested Array: This term refers to arrays that contain other arrays as their elements.
Rows refer to the horizontal lines in a table or grid that contain data. They represent individual records or entries in a dataset.
Columns: Columns are the vertical lines in a table or grid that contain data. They represent different attributes or variables associated with each record.
Indices: Indices are used to identify and locate specific rows within a dataset. They act as reference points for accessing and manipulating data efficiently.
Records: Records are complete sets of related information stored within a single row of a database or spreadsheet. Each record represents an individual entity or item.
Double-index notation is a way of representing elements in a two-dimensional array using two indices, one for the row and one for the column. It allows easy access to specific elements within the array.
Single-index notation: A way of representing elements in a one-dimensional array using only one index.
Two-dimensional array: An array that stores data in rows and columns, forming a grid-like structure.
Element access: The process of retrieving or modifying an element within an array using its index values.
A 0-indexed language is a programming language where arrays and other data structures start counting from 0 instead of 1. In these languages, the first element is accessed with an index of 0.
Indexing error: An error that occurs when accessing an element outside the valid range of indices in an array or other data structure.
Off-by-one error: A common mistake where programmers accidentally use incorrect indices due to confusion between zero-based indexing and one-based indexing.
Loop iteration: The process of repeatedly executing code based on incrementing or decrementing an index variable.
Graphical representation involves using visual elements such as charts, graphs, or diagrams to present information or data visually.
Data Visualization: It is the process of creating visual representations of data to communicate patterns, trends, or insights effectively.
Bar Graph: A type of graphical representation that uses rectangular bars to compare different categories or values.
Line Graph: This type of graph shows how data changes over time by connecting points with lines.