JAVA Syllabus
QUESTIONS & ANSWERS

What is Multi-Dimensional array in Java, explain with an example?

In Java, a multi-dimensional array is an array of arrays. It is a way to represent data in a table or matrix-like structure where the elements are arranged in rows and columns.

To create a multi-dimensional array in Java, you can use the following syntax:

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

Here, dataType can be any valid Java data type, such as int, double, String, etc. arrayName is the name of the array, and rows and columns specify the size of the array. For example, to create a 2-dimensional array of integers with 3 rows and 4 columns, you can use the following code:

int[][] myArray = new int[3][4];

This creates a 2D array with 3 rows and 4 columns, where each element is initialized to 0.

To access an element in a multi-dimensional array, you can use the index of the row and column. For example, to access the element in the second row and third column of myArray, you can use the following code:

int element = myArray[1][2];

This will retrieve the value of the element in the second row and third column, which is the element at index [1][2] of the array.

You can also loop through a multi-dimensional array using nested loops. For example, to print all the elements of myArray, you can use the following code:

for (int i = 0; i < myArray.length; i++) {
    for (int j = 0; j < myArray[i].length; j++) {
        System.out.print(myArray[i][j] + " ");
    }
    System.out.println();
}

This will print each element of the array, separated by a space, with each row on a new line.

Overall, multi-dimensional arrays in Java are a powerful way to represent complex data structures and are commonly used in applications such as image processing, simulation, and scientific computing.

25/03/2023, 5:55 am Read : 223 times