File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes array! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "array!" Watch "array!" New topic


Sridhar Srinivasan
Ranch Hand

Joined: Nov 07, 2003
Posts: 117
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

Joined: Jan 21, 2004
Posts: 92
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 ?

"Did anyone understand what I have just explained? ... because I did not!"
Rama Kumar PV

Joined: Dec 26, 2003
Posts: 26
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.
[ February 03, 2004: Message edited by: Rama Kumar PV ]
Sridhar Srinivasan
Ranch Hand

Joined: Nov 07, 2003
Posts: 117
Thanks for all your reply.I think that the answer given by me was rite..
Davy Kelly
Ranch Hand

Joined: Jan 12, 2004
Posts: 384
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.

How simple does it have to be???
I agree. Here's the link:
subject: array!
It's not a secret anymore!