0
0
JavaConceptBeginner · 3 min read

What is 2D Array in Java: Explanation and Example

A 2D array in Java is an array of arrays, which means it stores data in a grid or table-like structure with rows and columns. It allows you to organize data in two dimensions, like a spreadsheet, using syntax like int[][] arrayName.
⚙️

How It Works

Think of a 2D array in Java as a collection of rows, where each row itself is an array. Imagine a chessboard: it has rows and columns, and each square can hold a value. Similarly, a 2D array holds values arranged in rows and columns.

In Java, a 2D array is actually an array where each element is another array. This means you can access data by specifying two indexes: the first for the row, and the second for the column. For example, array[1][2] accesses the element in the second row and third column.

This structure helps organize data that naturally fits into a grid, like tables, matrices, or game boards.

💻

Example

This example creates a 2D array of integers with 3 rows and 3 columns, assigns values, and prints them in a grid format.

java
public class TwoDArrayExample {
    public static void main(String[] args) {
        int[][] matrix = new int[3][3];

        // Assign values
        matrix[0][0] = 1;
        matrix[0][1] = 2;
        matrix[0][2] = 3;
        matrix[1][0] = 4;
        matrix[1][1] = 5;
        matrix[1][2] = 6;
        matrix[2][0] = 7;
        matrix[2][1] = 8;
        matrix[2][2] = 9;

        // Print the 2D array
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output
1 2 3 4 5 6 7 8 9
🎯

When to Use

Use a 2D array when you need to store data in a grid or table format. This is common in situations like:

  • Storing pixel values in images
  • Representing game boards like chess or tic-tac-toe
  • Handling matrices in math calculations
  • Organizing data in rows and columns, such as seating charts or schedules

They help keep related data grouped logically and make it easy to access elements by their row and column positions.

Key Points

  • A 2D array is an array of arrays, creating a grid-like structure.
  • Access elements using two indexes: array[row][column].
  • Useful for organizing data in rows and columns.
  • Can be used for matrices, game boards, tables, and more.

Key Takeaways

A 2D array stores data in rows and columns using an array of arrays.
Access elements with two indexes: first for row, second for column.
Ideal for grid-like data such as tables, matrices, and game boards.
Java syntax for 2D arrays uses double square brackets, e.g., int[][] array.
You can loop through rows and columns to read or modify data.