Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

mock exam question

 
James Noi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
simbagoo,
Welcome to Javaranch, a friendly place for Java greenhorns
You should try to compile this code and see what the result is. Then we can discuss if you still have problems with this code. Remember that practicing is very important for any Java programmer.
We ain't got many rules 'round these parts, but we do got one. Please change your displayed name to comply with the JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!
 
Bill Ngu
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I haven't try to compile that code.. but is the answer 2 ?
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is indeed 2
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
array index in Java starts with 0 not 1, so anar[1] means the second element in the array
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I meant 2 is what gets printed out, so the correct answer is 3
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic