• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K & B Book Chapter 10 Question 12

 
Serg Masow
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

the selftest question 12 of chapter 10 looks like this:


And the following sub-directory structure:
test
|--UseKit.class
|
com
|--KitJar.jar

If the current directory is test, and the file pkg/Kit.class is in KitJar.jar, which
command line will produce the output bc ? (Choose all that apply.)

A. java UseKit b c
B. java UseKit a b c
C. java -classpath com UseKit b c
D. java -classpath com:. UseKit b c
E. java -classpath com/KitJar.jar UseKit b c
F. java -classpath com/KitJar.jar UseKit a b c
G. java -classpath com/KitJar.jar:. UseKit b c
H. java -classpath com/KitJar.jar:. UseKit a b c

Answer given:
H is correct.
A, C, E, and G are incorrect if for no other reason than args[] is 0-based.
B, D, and F are incorrect because java needs a classpath that specifies two directories, one
for the class file (the . directory), and one for the JAR file (the com directory). Remember,
to find a JAR file, the classpath must include the name of the JAR file, not just its directory.

I have a question to the option F.
The answer F is wrong because the classpath doesn't contain the current directory (.) and the Java virtual machine (invocation java [options] class [args]) doesn't look in the current directory by default if it load a .class file. This explanation is understandable.

But why if the current directory is test an I have some class file there e.g. Foo.class and I make following invocation

java -classpath /dirOtherThanTest Foo

the Foo class is loaded and executed without problem? There is more if the Foo.class need a further class for the execution e.g. Bar.class, which resides in the same driectory test and the same invocation is used:

java -classpath /dirOtherThanTest Foo

it also works without problem? Can anyone explain why it work, the current directory isn't defined in the -classpath but java can find and execute the .class files anyway?

kind regards
Serg
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the directory you list in the CLASSPATH, is there a class named Foo.class?
 
Serg Masow
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Keith,

there is no CLASSPATH defined on my machine. But I found out some interesting thing. I have Windows as operating system and if I invoke java like this

java -classpath c: Foo

or without classpath flag at all like this

java Foo

it finds the Foo.class and executes it correctly when it exists in the current directory. But the invocation

java -classpath c:\ Foo

where Foo is in another dir as c:\ ends with a NoClassDefFoundError as expected...
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic