2D Arrays Basics
Part of the Logic & Flow section of Coddy's Java journey — lesson 1 of 59.
In Java, a 2D array is an array of arrays, forming a grid or a matrix-like structure. It's like a table with rows and columns, where each cell can hold a value. 2D arrays are useful for representing data that has a two-dimensional relationship, such as a chessboard, a seating chart, or a grid-based game.
Here's how you declare and initialize a 2D array in Java:
data_type[][] arrayName = new dataType[numberOfRows][numberOfColumns];dataType: The type of elements the array will hold (e.g.,int,String, etc.).arrayName: The name you give to the array.numberOfRows: The number of rows in the array.numberOfColumns: The number of columns in the array.
For example, to create a 2D array of integers with 3 rows and 4 columns, you would write:
int[][] matrix = new int[3][4];You can also initialize a 2D array with values directly:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};Challenge
EasyInitialize a 2D array with the following value:
5, 7, 10, 24, 41
86, 13, 683, 64, 13
42, 46, 791, 111, 9
86, 88, 1845, 5, 15897
9, 1, 5, 5, 6Cheat sheet
A 2D array in Java is an array of arrays, forming a grid structure with rows and columns.
Declaration and initialization:
data_type[][] arrayName = new dataType[numberOfRows][numberOfColumns];Example with empty array:
int[][] matrix = new int[3][4];Initialize with values directly:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};Try it yourself
public class Main {
public static void main(String[] args) {
int[][] matrix = {
// Write your code here
};
// Print the matrix
int rows = matrix.length;
int cols = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap