• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt(marcus mock test)

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Sandra Marti
I compiled the program, and now I understand which are legal ways to intialise an array.
regards
VR
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic