• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array!

 
Sridhar Srinivasan
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I gave the answer for this as 3)
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
Can anybody explain this please! Thanks.
 
Dan Andrei
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not see a problem here, you gave the correct answer.
the format here :
int anar[]=new int[]{1,2,3} is also known as anonymus array initilializer,
what was THEIR ANSWER ?
 
Rama Kumar PV
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sridhar,
Please insert your code sample using the CODE button option in Instant UBB Code.
Your code sample gives 2 as the output as you thought, because of the definition of the anonymous array,
int anar[]=new int[]{1,2,3};
You need not give the size of the array using the above array definition format. As the array index starts from 0, anar[1] will print out 2.
Cheers,
Rama
[ February 03, 2004: Message edited by: Rama Kumar PV ]
 
Sridhar Srinivasan
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for all your reply.I think that the answer given by me was rite..
 
Davy Kelly
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah you got it right, cause i did the same question yesterday, if i remember correctly it is one of the Dan or Marcus' questions.
Davy
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic