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 Question 51 from Marcus Green Mock 1 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 "Question 51 from Marcus Green Mock 1" Watch "Question 51 from Marcus Green Mock 1" New topic

Question 51 from Marcus Green Mock 1

Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2591

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?

- Manish
Jamal Hasanov
Ranch Hand

Joined: Jan 08, 2002
Posts: 411
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)
I agree. Here's the link:
subject: Question 51 from Marcus Green Mock 1
It's not a secret anymore!