Java array definitions
Was doing multiple choices and one question gave the following array definitions and asked which ones are valid:
int[] array1, array2[];
int[][] array3;
int[] array4[], array5[];
A. array2 = array3;
B. array2 = array4;
C. array1 = array2;
D. array4 = array1;
E. array5 = array3;
And the correct answers are: A, B, E. Why? I can see that array3 and array4 are 2 dimensional arrays, while array1,2,5 are not.
+3
source to share
2 answers
Split the definition of each variable into a line, and then you will understand how each operation compiles (or not):
int[] array1; int[] array2[]; //which is int[][] array2 int[][] array3; int[] array4[]; //which is int[][] array4 int[] array5[]; //which is int[][] array5
Now you can easily evaluate them:
A. array2 = array3; //compiles
B. array2 = array4; //compiles
C. array1 = array2; //doesn't compile
D. array4 = array1; //doesn't compile
E. array5 = array3; //compiles
Also, there are no 2D arrays in Java. You have an array of arrays.
+8
source to share
int[] array1, array2[];
int[][] array3;
int[] array4[], array5[];
array1 is a one-dimensional array
array2 is now a 2dimension array, and array 4 and array 5 array3 is also declared as a 2d array
array 1 does not match any other array in the list
array 2 can = array3, array4 or array5 and vice versa.
0
source to share