• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array declaration doubt

 
Vivian Josh
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I found one question Arrays. It goes like this :

Which of these statements are legal. Select the three correct answers.


A. int arr[][] = new int[5][5];

B. int[]arr[] = new int[5][5];

C. int[] arr = new int[5][];

D. int[] arr = new int[][5];

ANS : A, B, c

I think 'C' is incorrect way of declaring array. Can anyone confirm me that? I tried compiling it and gave me a compilation error on jdk 1.6 . Is it a valid way on jdk 1.4 and prior versions?

Link to the question

http://www.simulationexams.com/SampleQuestions/java-certification/scjp/scjp_q1.htm

Thanks in advance.

- Vivian
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are correct: C is wrong. It declares the variable "arr" as an array of ints, and then tries to assign an array of arrays to it, resulting in a compiler error of "incompatible types."
 
Vivian Josh
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks marc ! It boost my confidence
 
Deepa More
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please tell me the difference between options C and D ?

Thanks
Deepa
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marc,

Option D also seems to be wrong right. It does not specify the size of rows but just columns. How about that?
 
Akhilesh Trivedi
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Muthu!
C & D can be discarded on incompatible type itself. On left hand side there is single dimensional array while on right hand side it is two dimensional.

Deepa!
You need not worry about the difference as the declarations are wrong. However if you were to worrry for if code was

int [] [] arr

on left hand side.
D would still fail as per muthu's reply. i.e. in case of multi-dimensional arrays you need to specify all sizes (with or without the one in last bracket.) You can do away with last bracket but not prior to that.
[ July 02, 2007: Message edited by: Akhilesh Trivedi ]
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats fine Akilesh. Thank you.

Deepa,

When constructing the arrays of more than 1D, you can omit the column (from the rightmost) but not the rows, as thats the only way to tell the compiler about the size of the array.

HtH.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic