File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Mock Exam Errata and the fly likes Markus, exam 1 Q51 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "Markus, exam 1 Q51" Watch "Markus, exam 1 Q51" New topic
Author

Markus, exam 1 Q51

Jeff L.
Greenhorn

Joined: Sep 02, 2003
Posts: 8
What will happen when you compile and run the following code?
public class Scope{ private int i; public static void main(String argv[]){Scope s = new Scope();s.amethod(); }//End of main public static void amethod(){System.out.println(i); }//end of amethod}//End of class
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
-------------------->
In the official answer, 3 is preferred over 4 because:
"...Thus you will get an error saying something like
Can't make a static reference to a non static variable"
I thought that scope was defined as the set of code locations where a particular variable is usable, and static vs. non-static is one of the determiners of scope, so I would consider the official answer to support option 4 as being superior to option 3.
Is this not what scope means?
Ana Abrantes
Ranch Hand

Joined: Sep 04, 2003
Posts: 43
But you can only refer to a non-static member through an instance of the class.
Static is not a scope, it says that the method/variable is related to the class and not the instance, so how can you refer to an instance variable if you don't have an instance related to it?
That's the point and not scope.
It would work if you changed like this:
public class Scope{
private int i;
public static void main(String argv[]){
Scope s = new Scope();
amethod(s);
}//End of main
public static void amethod(Scope s){
System.out.println(s.i);
}//end of amethod
}//End of class
Ana


Ana<p>SCJP 1.4
Ana Abrantes
Ranch Hand

Joined: Sep 04, 2003
Posts: 43
There's another possible solution:
public class Scope{
private int i;
public static void main(String argv[]){
Scope s = new Scope();
System.out.println(s.i);
}//End of class
Ana
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Markus, exam 1 Q51