Reputation: 73
In the book "OCA Oracle Certified Associate Java SE 8 Programmer I Study Guide Exam 1Z0-808" by Boyarsky and Selikoff I encountered a confusing question in the review exam for Chapter I:
14. Given the following class in the file /my/directory/named/A/Bird.java:
INSERT CODE HERE
public class Bird { }
Which of the following replaces INSERT CODE HERE
if we compile from /my/directory? (Choose all that apply)
A. package my.directory.named.a;
B. package my.directory.named.A;
C. package named.a;
D. package named.A;
E. package a;
F. package A;
G. Does not compile
The book states that the correct answer is just D. (we'll ignore the fact that they wrote "Choose all that apply" despite stating that they would only do so if there were more than 1 answer, earlier in the book), with the explanation:
D. The package name represents any folders underneath the current path, which is named.A in this case. Option B is incorrect because package names are case sensitive, just like variable names and other identifiers.
I'm totally confused with this on various levels:
I tried to compile the file from /my/directory using javac /named/A/Bird.java
and the code compiles successfully with any of the answers above. Furthermore, the code compiles no matter what I write after package
in the first line of the class.
Let's assume I completely missed the point in (no pun intended) point 1 and that's not how we compile from /my/directory, then I've got these questions:
How do we compile from /my/directory?
Why is the option B. incorrect? The explanation they provided for B. makes no sense, obviously.
Can someone shed some light on this matter?
Upvotes: 7
Views: 1664
Reputation: 73568
The short answer is the question is wrong.
A single class can be compiled from anywhere, without considering the package hierarchy if it has no references to other custom classes (so you can use String
etc.). This is because it doesn't need to do any lookups for other classes, so there's no need for anything special in the compile-time classpath. As soon as you add a reference to let's say class named.A.Rock
the compilation will no longer work, because the directory hierarchy doesn't match the package hierarchy (unless you put Bird
in named.A
package as well).
So the example in the question is just bad. As soon as you add a reference to another class and the package hierarchy starts to matter, D
is the correct answer. The question is a bit poor since you can set the compile time classpath explicitly, at which point the concept of "current directory" doesn't matter one bit and all of the answers would be valid.
Upvotes: 5