Java
Programming
Syntax
Two-dimensional Array
Coding in Java

Syntax for creating a two-dimensional array in Java

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In Java, a two-dimensional array is essentially an array of arrays, where each element within the main array is also an array. These are often used in scenarios where you need a matrix, a table, or any kind of grid structure. Two-dimensional arrays can store values of a designated type, and they can be manipulated to perform various data operations, such as sorting, searching, or complex mathematical computations.

Declaring a Two-Dimensional Array

To declare a two-dimensional array in Java, you specify the type of elements the array will hold, followed by two pairs of square brackets. Here is how you can declare a two-dimensional array that will store integer values:

java
int[][] matrix;

Instantiating a Two-Dimensional Array

After declaring an array, you must instantiate it using the new keyword before you can use it. When instantiating, you need to specify the size of the array in terms of rows and columns:

java
matrix = new int[5][10]; // a 5x10 integer array

Here, matrix has 5 rows and 10 columns. You can access the array's elements using row and column indices, which start at 0. For example, to access the element at the first row and first column, you use:

java
int firstElement = matrix[0][0];

Initializing a Two-Dimensional Array

There are multiple ways to initialize a two-dimensional array in Java. You can either initialize it statically upon declaration or dynamically using loops.

Static Initialization:

java
1int[][] predefinedMatrix = {
2    {1, 2, 3},
3    {4, 5, 6},
4    {7, 8, 9}
5};

This piece of code creates a 3x3 matrix filled with the numbers from 1 to 9. Each row is defined within curly braces, and the entire set is enclosed in another pair of braces.

Dynamic Initialization:

If you want to fill the array with user input or based on some function, you can use loops:

java
1for(int i = 0; i < matrix.length; i++) {
2    for(int j = 0; j < matrix[i].length; j++) {
3        matrix[i][j] = i * j;  // Example: multiplicative table
4    }
5}

Array Dimensions

A two-dimensional array need not be symmetrical, meaning the length of each row can differ:

java
1int[][] jaggedArray = new int[4][];
2jaggedArray[0] = new int[5];
3jaggedArray[1] = new int[3];
4jaggedArray[2] = new int[8];
5jaggedArray[3] = new int[2];

This code initiates a so-called jagged array, or ragged array, where each row has a different length.

Common Operations

Common operations with two-dimensional arrays involve manipulating individual elements, iterating through arrays, and multi-dimensional slicing for subarrays.

For example, to print all elements:

java
1for (int[] row : matrix) {
2    for (int element : row) {
3        System.out.print(element + " ");
4    }
5    System.out.println(); // moves to the next line for each row
6}

Summary Table of Key Points:

Key AspectDetail
Declarationtype[][] arrayName;
InstantiationarrayName = new type[rows][cols];
Static Initializationtype[][] arrayName = &#123;&#123;val1, val2&#125;, &#123;val3, val4&#125;&#125;;
Dynamic InitializationUse nested loops to assign values array[i][j] = value;
Accessing ElementsarrayName[i][j] where i and j denote the row and column index, respectively.
Jagged ArraysCreating arrays with rows of variable lengths int[][] array = new int[rows][];

Understanding and utilizing two-dimensional arrays effectively can significantly enhance the ability to solve problems that involve complex data structures or require simulation of spatial arrangements.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.