Java Multi-Dimensional Arrays
Last Updated : 08 Jan, 2025
A multidimensional array can be defined as an array of arrays.
Multidimensional arrays in Java are not stored in tabular form. Each row is
independently heap allocated, making it possible to have arrays with
different row sizes.
Example:
// Java Program to Demonstrate
// Multi Dimensional Array
import java.io.*;
public class Main {
public static void main(String[] args){
int[][] arr = new int[10][20];
arr[0][0] = 1;
System.out.println("arr[0][0] = " + arr[0][0]);
}
}
Output
arr[0][0] = 1
Syntax for Multi-Dimensional Array
data_type[1st dimension][2nd dimension][]..[Nth dimension]
array_name = new data_type[size1][size2]….[sizeN];
Parameters:
data_type: Type of data to be stored in the array. For example: int,
char, etc.
dimension: The dimension of the array created. For example: 1D, 2D,
etc.
array_name: Name of the array
size1, size2, …, sizeN: Sizes of the dimensions respectively.
Examples:
// Two dimensional array:
int[][] twoD_arr = new int[10][20];
// Three dimensional array:
int[][][] threeD_arr = new int[10][20][30];
Size of Multidimensional Arrays: The total number of elements that
can be stored in a multidimensional array can be calculated by
multiplying the size of all the dimensions.
For example: array int[][][] x = new int[5][10][20] can store a total
of (5*10*20) = 1000 elements.
Two – Dimensional Array (2D-Array)
Two – dimensional array is the simplest form of a multidimensional array.
A 2-D array can be seen as an array storing multiple 1-D array for easier
understanding.
Syntax (Declare, Initialize and Assigning)
// Declaring and Intializing
data_type[][] array_name = new data_type[x][y];
// Assigning Value
array_name[row_index][column_index] = value;
Representation of 2D Array in Tabular Format
A 2-D array can be seen as a table with ‘x’ rows and ‘y’ columns where
the row number ranges from 0 to (x-1) and column number ranges from 0
to (y-1). A 2-D array ‘x’ with 3 rows and 3 columns is shown below:
Example 1: We can add the values directly to the array while declaring
the array.
// Java Program to demonstrate the use of
// Two Dimensional Array
import java.io.*;
class Main {
public static void main(String[] args){
// Array Intialised and Assigned
int[][] arr = { { 1, 2 }, { 3, 4 } };
// Printing the Array
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++)
System.out.print(arr[i][j]+" ");
System.out.println();
}
}
}
Output
1 2
3 4
Example 2: Here we can update the values while executing works both
ways can be accepted by user or by some variable.
// Java Program to demonstrate the use of
// Two Dimensional Array
public class TwoDArray {
public static void main(String[] args) {
// Row and Columns in Array
int n = 2;
int m = 2;
// Array declared and initialized
int[][] arr = new int[n][m];
int it = 1;
// Assigning the values to array
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = it;
it++;
}
}