Java OCA OCP Practice Question 371

Question

Which of these array declarations and instantiations are legal?

Select 4 options

A. int[] a[] = new int[5][4] ; 
B. int a[][] = new int[5][4] ; 
C. int a[][] = new int[][4] ; 
D. int[] a[] = new int[4][] ; 
E. int[][] a = new int[5][4] ; 


Correct Options are  : A B D E

Note

A. int [] a [] = new int [5][4] ;

This will create an array of length 5.

Each element of this array will be an array of 4 ints.

B. int a [][] = new int [5][4] ;

This will create an array of length 5.

Each element of this array will be an array of 4 ints.

C. int a [][] = new int [][4] ;

The statement int[][4] will not compile,

because the dimensions must be created from left to right.

D. int [] a [] = new int [4][] ;

This will create an array of length 4.

Each element of this array will be null.

But you can assign an array of ints of any length to any of the elements.

E. int [][] a = new int [5][4] ;

This will create an array of length 5.

Each element of this array will be an array of 4 ints.

The [] notation can be placed both before and after the variable name in an array declaration.

int[] ia, ba; // here ia and ba both are int arrays. 
int ia[], ba; //here only ia is int array and ba is an int. 

Multidimensional arrays are created by creating arrays that can contain references to other arrays .




PreviousNext

Related