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

Question 51 from Marcus Green Mock 1

 
Manish Hatwalne
Ranch Hand
Posts: 2595
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q51 Marcus Green Mock 1
What will happen when you compile and run the following code?


1) A value of 0 will be printed out
2) Nothing will be printed out
3) A compile time error
4) A compile time error complaining of the scope of the variable i
Answer and Explanation -
3) A compile time error
Because only one instance of a static method exists not matter how many instance of the class exists it cannot access any non static variables. The JVM cannot know which instance of the variable to access. Thus you will get an error saying something like
Can't make a static reference to a non static variable
========================================================================
When I had to make decision between (3) and (4) I thought answer (4) is more specific. Isn't
static accessing non-static variable related to scope of the variable, or am I wrong in this assumption?
Is there something *most elementary* that I am missing?

TIA,
- Manish
 
Jamal Hasanov
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Answer (4) means that you cannot access variable i inside method due to its private modifier. But this is not true: variables with private modifier are accessible inside class.
But the reason of compile-time error is ACCESSING TO NON STATIC VARIABLE INSIDE STATIC METHOD. That's why answer is (3)
Jamal
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic