JavaArrays

Two-Dimensional Arrays in Java

Learn two-dimensional arrays in Java to store data in rows and columns, including declaration, initialization, traversal, and practical examples.

Two-Dimensional Arrays in JavaLink to this section

A two-dimensional array in Java is an array of arrays. It is used to store data in a row and column format, similar to a table or matrix.

Two-dimensional arrays are commonly used in applications such as matrices, game boards, and tabular data processing.

Structure of Two-Dimensional ArraysLink to this section

A two-dimensional array consists of rows and columns. Each element is accessed using two indexes: one for the row and one for the column.

Example explanation: If an array has 3 rows and 4 columns, valid indexes are from [0][0] to [2][3].

note

Rows and columns are zero-indexed in Java.

Declaring Two-Dimensional ArraysLink to this section

Declaring a two-dimensional array specifies the data type and reference variable.

Initializing Two-Dimensional ArraysLink to this section

Two-dimensional arrays can be initialized in different ways.

warning

Once defined, the number of rows is fixed, but column sizes can vary in jagged arrays.

Accessing Elements in Two-Dimensional ArraysLink to this section

Elements are accessed using both row and column indexes.

warning

Invalid row or column indexes result in ArrayIndexOutOfBoundsException.

Traversing Two-Dimensional ArraysLink to this section

Traversal is usually done using nested loops.

tip

Use array.length for rows and array[i].length for columns.

Jagged Arrays in JavaLink to this section

A jagged array is a two-dimensional array where each row can have a different number of columns.

note

Jagged arrays help optimize memory when data size varies per row.
Two-Dimensional Arrays in Java
Question 1 of 5

How many indexes are required to access an element in a two-dimensional array?

Two-Dimensional Arrays in Java

medium
  1. Create a 2D array representing a 3×3 matrix and print it.
  2. Write a program to find the sum of all elements in a two-dimensional array.
  3. Find the transpose of a matrix using a two-dimensional array.
  4. Create a jagged array to store marks of students in different subjects.
  5. Explain the difference between a rectangular array and a jagged array with examples.