Which of the following is the correct way to declare a multidimensiona...
The syntax to declare multidimensional array in java is either int[][] arr; or int arr[][];
Which of the following is the correct way to declare a multidimensiona...
Correct way to declare a multidimensional array in Java
The correct way to declare a multidimensional array in Java is option 'c' - int[][] arr.
Explanation:
In Java, a multidimensional array is an array of arrays. It allows you to store data in a tabular form, with rows and columns.
Syntax:
To declare a multidimensional array in Java, you use the following syntax:
datatype[][] arrayName;
Here, 'datatype' represents the type of data that the array will hold, and 'arrayName' is the name given to the array. The number of square brackets '[]' represents the number of dimensions in the array.
Examples:
Let's consider a few examples to understand the syntax and declaration of multidimensional arrays in Java.
1. Declaring a 2D array:
To declare a 2D array, you can use the following syntax:
int[][] arr;
This declares a 2D array named 'arr' that can hold integer values.
2. Declaring a 3D array:
To declare a 3D array, you can use the following syntax:
int[][][] arr;
This declares a 3D array named 'arr' that can hold integer values.
3. Declaring a rectangular multidimensional array:
In Java, multidimensional arrays can be rectangular, meaning that each row has the same number of columns. For example, to declare a rectangular 2D array with 3 rows and 4 columns, you can use the following syntax:
int[][] arr = new int[3][4];
This creates a 2D array named 'arr' with 3 rows and 4 columns, where each element is initialized to the default value of 0.
4. Declaring an irregular multidimensional array:
Java also allows you to declare irregular multidimensional arrays, where each row can have a different number of columns. To declare an irregular 2D array, you can use the following syntax:
int[][] arr = new int[3][];
This declares a 2D array named 'arr' with 3 rows, but the number of columns is not specified. You can later assign different column lengths to each row.
In conclusion, the correct way to declare a multidimensional array in Java is option 'c' - int[][] arr.