Skip to content

2D arrays

A 2D array in Java is an array of arrays, where each element of the primary array is itself an array. This structure is often used to represent tabular data, such as matrices or grids.


Key Features of 2D Arrays

  1. Declaration and Initialization:
    1. Can have fixed dimensions or dynamically sized rows.
  2. Rectangular Arrays:
    1. All rows have the same number of columns.
  3. Jagged Arrays:
    1. Rows can have different lengths (not all rows must have the same number of columns).
  4. Zero-Based Indexing:
    1. Both rows and columns are indexed starting from 0.

Syntax

Declaration

dataType[][] arrayName;

Initialization

// Fixed-size 2D array

arrayName = new dataType[rows][columns];

// Declaration and initialization in one step

dataType[][] arrayName = new dataType[rows][columns];

Alternative Declaration

dataType arrayName[][]; // Valid but less common

dataType[] arrayName[]; // Valid but less common


Accessing Elements

Each element is accessed using two indices:

  • First index: Row number.
  • Second index: Column number.

Example:

arrayName[rowIndex][columnIndex];


Example 1: Fixed-Size 2D Array

public class Main {

    public static void main(String[] args) {

        // Declare and initialize a 2D array

        int[][] matrix = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };

        // Display the array

        System.out.println(“Matrix:”);

        for (int i = 0; i < matrix.length; i++) {         // Iterating rows

            for (int j = 0; j < matrix[i].length; j++) {  // Iterating columns

                System.out.print(matrix[i][j] + ” “);

            }

            System.out.println(); // Newline after each row

        }

    }

}

Output:

Matrix:

1 2 3

4 5 6

7 8 9


Example 2: Dynamic 2D Array (Jagged Array)

In a jagged array, rows can have different lengths.

public class Main {

    public static void main(String[] args) {

        // Declare a jagged array

        int[][] jaggedArray = new int[3][];

        jaggedArray[0] = new int[]{1, 2};        // Row 0 with 2 elements

        jaggedArray[1] = new int[]{3, 4, 5};    // Row 1 with 3 elements

        jaggedArray[2] = new int[]{6};          // Row 2 with 1 element

        // Display the jagged array

        System.out.println(“Jagged Array:”);

        for (int i = 0; i < jaggedArray.length; i++) {

            for (int j = 0; j < jaggedArray[i].length; j++) {

                System.out.print(jaggedArray[i][j] + ” “);

            }

            System.out.println();

        }

    }

}

Output:

Jagged Array:

1 2

3 4 5

6


Operations on 2D Arrays

1. Initializing with Loops

2D arrays can be initialized using nested loops.

public class Main {

    public static void main(String[] args) {

        int rows = 3, cols = 3;

        int[][] array = new int[rows][cols];

        // Fill array with sequential numbers

        int value = 1;

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < cols; j++) {

                array[i][j] = value++;

            }

        }

        // Display the array

        System.out.println(“Filled Array:”);

        for (int[] row : array) {  // Enhanced for-loop

            for (int num : row) {

                System.out.print(num + ” “);

            }

            System.out.println();

        }

    }

}

Output:

Filled Array:

1 2 3

4 5 6

7 8 9


2. Passing 2D Arrays to Methods

You can pass a 2D array to a method like any other object.

public class Main {

    static void print2DArray(int[][] array) {

        for (int[] row : array) {

            for (int num : row) {

                System.out.print(num + ” “);

            }

            System.out.println();

        }

    }

    public static void main(String[] args) {

        int[][] matrix = {

            {1, 2, 3},

            {4, 5, 6}

        };

        System.out.println(“Matrix:”);

        print2DArray(matrix);

    }

}

Output:

Matrix:

1 2 3

4 5 6


3. Returning 2D Arrays from Methods

A method can return a 2D array.

public class Main {

    static int[][] createMatrix(int rows, int cols) {

        int[][] matrix = new int[rows][cols];

        int value = 1;

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < cols; j++) {

                matrix[i][j] = value++;

            }

        }

        return matrix;

    }

    public static void main(String[] args) {

        int[][] result = createMatrix(2, 3);

        System.out.println(“Returned 2D Array:”);

        for (int[] row : result) {

            for (int num : row) {

                System.out.print(num + ” “);

            }

            System.out.println();

        }

    }

}

Output:

Returned 2D Array:

1 2 3

4 5 6


Applications of 2D Arrays

  1. Matrices: Representing mathematical matrices.
  2. Grids: Handling game boards like tic-tac-toe or chess.
  3. Tabular Data: Managing data in a tabular format, such as rows and columns of a database.
  4. Dynamic Structures: Creating jagged structures like triangular arrays.

Best Practices

  1. Avoid Hardcoding Sizes:
    1. Use array.length for rows and array[row].length for columns.
  2. Null Checks:
    1. Always check for null references in dynamic arrays.
  3. Enhanced Loops:
    1. Use enhanced for loops for cleaner traversal.

Conclusion

2D arrays in Java are versatile structures for handling tabular and grid-like data. They can represent both fixed-size and jagged configurations, making them suitable for a variety of applications. Understanding their declaration, initialization, and usage patterns is crucial for efficient programming.