Can please someone explain me? What will happen if you try to compile and run the following code? public class Q { public static void main(String argv[]){ int anar[]=new int[]{1,2,3}; System.out.println(anar[1]); } } 1) 1 2) Error anar is referenced before it is initialized 3) 2 4) Error: size of array must be defined answer: 3 ) 2 I think the array declaration is wrong. He gave int anar[]=new int[]{1,2,3}; Correct me if I am wrong. Thank you in advance. regards VR
Sandra Marti
Ranch Hand
Joined: Jun 08, 2000
Posts: 63
posted
0
VR, The answer given is absolutely right. Here the array is declared as well as initialised. Why don't you compile the program and run it? You will see it for yourself.
antraarora
Ranch Hand
Joined: Jul 27, 2000
Posts: 45
posted
0
The answer is absolutely right. The array has been declared and also initialized in one step. It is totally legal to say int anar[]={1,2,3} instead of int anar[]; anar[0]=1; anar[1]=2; anar[2]=3; It's the same thing. However be careful, this is wrong:- int anar[3]={1,2,3} Because you might think, well I am assigning the length of this array. But look carefully, you are actually assigning the index 3 of array anar as 3 values.......wrong!!!
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Thanks Sandra Marti and Antraarora What I thought is when he is declaring an array, he put [] after new int, and also gave numbers in curly brackets that's why I thought may it won't compile. int anar[]=new int[]{1,2,3}; Thanks VR
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Thank you Sandra Marti I compiled the program, and now I understand which are legal ways to intialise an array. regards VR