In Java, multi-dimensional arrays serve as a way to organize data into rows and columns. This section will cover the concept of multi-dimensional arrays, as well as the steps involved in declaring, initializing, and working with them within Java applications.
What are Multi-Dimensional Arrays in Java?
Arrays that are multi-dimensional are arrays containing arrays within them, where each element in the primary array stores another array. These types of arrays are frequently utilized to portray data in the format of tables or matrices, like grids, charts, or spreadsheets.
Think of a multi-dimensional array as similar to a spreadsheet. Consider a scenario where you are storing the scores of students. In this setup, each row corresponds to a specific student, and each column represents a different subject. This arrangement allows for the structured organization of information in rows and columns through the utilization of a multi-dimensional array.
Two-Dimensional (2D) Array
A two-dimensional (2D) array is a form of multi-dimensional array that organizes data into rows and columns. It is commonly utilized to depict structures resembling tables, like matrices, grids, or tables, where information is arranged in two dimensions exclusively.
Declaration
There are multiple syntax options available for declaring a two-dimensional array, such as:
DataType[][] arrayName;
DataType arrayName[][];
arrayName = new DataType[rows][columns];
Declaring and initializing a two-dimensional array can be done simultaneously in a single statement as shown below.
datatype[][] arrayName = new datatype[rows][columns];
Assigning Values (Initialization)
The following is the format for initializing a two-dimensional array:
arrayName[rows][columns] = {values};
Examples
// 2D Array with two rows and two columns Intialised and Assigned
int[][] arr = { { 1, 2 }, { 3, 4 } };
//array with three rows and three columns
int[][] arr = new int[3][3];
Representation of 2D Array
It is important to understand that Java follows zero-based indexing, which indicates that array indexing in Java begins at 0.
It's important to remember that within a multi-dimensional array, the rows can vary in size, allowing for each row to potentially contain a different number of elements.
Example of Two-Dimensional Array
An illustration below showcases the functionality of a two-dimensional array in the Java programming language.
Example
public class Main {
public static void main(String args[]) {
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
// Printing the 2D array
for (int i = 0; i < 3; i++) //loop for rows
{
for (int j = 0; j < 3; j++) //loop for columns
{
System.out.print(arr[i][j] + " "); //prints element with space
}
System.out.println(); //throws cursor to the next line
}
}
}
Output:
1 2 3
4 5 6
7 8 9
Explanation
Within the program provided, a 3x3 matrix has been declared and initialized. The initial for loop cycles through the rows while the subsequent loop iterates through the columns. The initial print command displays the array elements separated by spaces, and the following print function moves the cursor to a new line.
Two-Dimensional (2D) Array with User Input
In this instance, user-input values populate a two-dimensional array. Initially, the program establishes the number of rows and columns, followed by the user inputting elements for each position in the array. To achieve this, nested loops are utilized to iterate through the input values row-wise and column-wise. Subsequently, another set of nested loops is employed to exhibit the entered elements in a matrix format.
Example
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Define the dimensions of the array
System.out.print("Enter the number of rows:");
int rows = scanner.nextInt(); //reading number of rows from the user
System.out.print("Enter the number of columns:");
int columns = scanner.nextInt(); //reading number of columns from the user
// Initialize the 2D array
int[][] array = new int[rows][columns];
//reading array elements from the user
System.out.println("Enter the elements of the array:");
for (int i = 0; i < rows; i++) //loop for rows
{
for (int j = 0; j < columns; j++) //loop for columns
{
System.out.print("Enter element for position (" + i + ", " + j + "): ");
//reading array elements one by one
array[i][j] = scanner.nextInt();
}
}
// Printing the 2D array
System.out.println("The entered 2D array is:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
Output:
Enter the number of rows:3
Enter the number of columns:3
Enter the elements of the array:
Enter element for position (0, 0): 1
Enter element for position (0, 1): 2
Enter element for position (0, 2): 3
Enter element for position (1, 0): 4
Enter element for position (1, 1): 5
Enter element for position (1, 2): 6
Enter element for position (2, 0): 7
Enter element for position (2, 1): 8
Enter element for position (2, 2): 9
The entered 2D array is:
1 2 3
4 5 6
7 8 9
Three-Dimensional (3D) Array
A Three-Dimensional (3D) array is a data structure consisting of arrays nested within arrays, enabling the storage of data in three dimensions, which include layers, rows, and columns. It is frequently utilized for managing intricate data sets, like a series of matrices or data organized in multiple tiers.
It is a sophisticated type of a 2D array, meaning it represents an array containing multiple arrays in two dimensions.
Declaration
You have the option to declare a three-dimensional array using any of the syntaxes listed below:
DataType[][][] arrayName;
DataType arrayName[][][];
arrayName = new DataType[][][];
Declaring and initializing a three-dimensional array can be done in a single statement, demonstrated as shown below.
datatype[][][] arrayName = new datatype[][][];
Assigning Values (Initialization)
The following is the format for initializing a three-dimensional array:
arrayName[][][] = {values};
Representation of 3D Array
Example of Three-Dimensional (3D) Array
Let's use an example to illustrate how a three-dimensional array operates in the Java programming language.
Example
public class Main {
public static void main(String[] args)
{
//declaring and initializing three-dimensional array
int[][][] threeDArray = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};
//Print the elements of the 3D array
System.out.println("Elements of the 3D Array:");
for (int i = 0; i < threeDArray.length; i++) {
for (int j = 0; j < threeDArray[i].length; j++) {
for (int k = 0; k < threeDArray[i][j].length; k++) {
System.out.print(threeDArray[i][j][k] + " ");
}
System.out.println(); // Move to the next line for better readability
}
System.out.println(); // Add a blank line between blocks
}
}
}
Output:
Elements of the 3D Array:
1 2 3
4 5 6
7 8 9
10 11 12
Size of Multidimensional Arrays
The dimensions of a multi-dimensional array are determined by the quantity of elements it holds in each dimension. In a two-dimensional array, the size is defined by the number of rows and columns, whereas in a three-dimensional array, it is influenced by layers, rows, and columns.
The length attribute is utilized to determine the dimensions of an array. In the case of a multidimensional array, accessing array.length provides the count of rows (or the first dimension), while array[row].length indicates the quantity of columns in a particular row.
Example
In this illustration, a two-dimensional array is generated with numerous rows and columns. The length attribute is employed to retrieve the quantity of rows, while array[row].length is employed to retrieve the number of columns in each row.
public class Main {
public static void main(String[] args) {
// Creating a 2D array
int[][] arr = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
// Number of rows
System.out.println("Number of rows: " + arr.length);
// Number of columns in each row
for (int i = 0; i < arr.length; i++) {
System.out.println("Number of columns in row " + i + ": " + arr[i].length);
}
}
}
Output:
Number of rows: 3
Number of columns in row 0: 3
Number of columns in row 1: 2
Number of columns in row 2: 4