0
0
JavaHow-ToBeginner · 3 min read

How to Create 2D Array in Java: Syntax and Examples

In Java, you create a 2D array using the syntax type[][] arrayName = new type[rows][columns];. This creates a grid-like structure where you can store data in rows and columns.
📐

Syntax

The basic syntax to create a 2D array in Java is:

  • type[][] arrayName; declares a 2D array variable.
  • new type[rows][columns]; creates the array with specified rows and columns.
  • You can combine declaration and creation in one line.
java
int[][] matrix = new int[3][4];
💻

Example

This example creates a 3x3 2D array, assigns values, and prints them row by row.

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

        // Assign values
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                grid[i][j] = i + j;
            }
        }

        // Print values
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(grid[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output
0 1 2 1 2 3 2 3 4
⚠️

Common Pitfalls

Common mistakes when creating 2D arrays include:

  • Forgetting to specify both dimensions when creating the array.
  • Mixing up row and column indexes when accessing elements.
  • Assuming all rows have the same length (Java allows jagged arrays).

Example of a wrong and right way:

java
int[][] wrong = new int[3]; // Wrong: missing second dimension

int[][] right = new int[3][4]; // Correct: rows and columns specified
📊

Quick Reference

ConceptSyntax ExampleDescription
Declarationint[][] arr;Declares a 2D array variable.
Creationarr = new int[2][3];Creates a 2D array with 2 rows and 3 columns.
Accessarr[0][1] = 5;Sets value at first row, second column.
Jagged Arrayint[][] jagged = { {1,2}, {3,4,5} };Rows can have different lengths.

Key Takeaways

Use type[][] name = new type[rows][columns]; to create a 2D array in Java.
Access elements with array[row][column] using zero-based indexes.
Java allows jagged arrays where rows can have different lengths.
Always specify both dimensions when creating the array to avoid errors.
Use nested loops to assign or read values from 2D arrays.