3

Was doing some multiple choices and one question gave the following array definitions and asking which are valid statements:

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 see array3 and array4 are 2 dimensional arrays and array1,2,5 are not.

3
  • 4
    Whether exams like this one will produce better programmers is something I'd dearly like to discuss with the examiner. Commented Dec 30, 2014 at 17:40
  • @laune they're not meant to provide better programmers, but to help programmers to spot these things and rewrite them. Commented Dec 30, 2014 at 17:47
  • @LuiggiMendoza You are an optimist, but that's not a bad property ;-) Commented Dec 30, 2014 at 17:58

2 Answers 2

8

Split the definition of each variable per line and then you will realize 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 these:

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, in Java, there are not 2 dimensional arrays. You have array of arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

@DavidColer that's not 2d array, that's an array of arrays. And there's no 3d array, it's array of arrays of arrays.
0
int[] array1, array2[];
int[][] array3;
int[] array4[], array5[];

array1 is a single dimension array

array2 is now a 2dimension array as well as array4 and array 5 array3 is also declared as a 2d array

array 1 does not equal any other array in the list

array 2 can = array3, array4, or array5 and vice versa.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.