Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

mock exam question

 
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
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • 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!
 
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
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is indeed 2
 
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
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • 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
 
I'm THIS CLOSE to ruling the world! Right after reading this tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic