What is 2D Array in Java: Explanation and Example
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.
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(); } } }
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.