Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Clarification on classpaths  RSS feed

richard rehl
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just want to make sure I understand this. From experimenting with an example in Chapter 10, if you have a class file:
which is saved in the directory:
and compiled into the directory:
Invoking java on MyClass.class won't work unless
A. you use the fully qualified name com/wickedlysmart/MyClass
B. you are in a directory at least one level above the package root (com), in this case, at least MyProject/classes.
C. Also, if you're currently in another subdirectory defined off the project root, in this case, MyProject/source, you can't say
java ../classes/com/wickedlysmart/MyClass without getting a compiler error.

edit: invoking
java -classpath ../classes com/wickedlysmart/MyClass
DOES work... so figured that one out

And, although SB say that adding a dot to the classpath will cause java to search the current directory, I find that if I'm currently in the directory:
invoking either "java -classpath . MyClass" or "java -classpath . com/wickedlysmart/MyClass" causes a NoClassDefFoundError, which seems to contradict what they say, which leads me to inference B above.
Siva Masilamani
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you put your class into a package then it should be refered with fully qualified name.

So in your case your class name is always "com.wickedlysmart.MyClass".

The confustion about the current directory:

Let say you stored this class under the folder:


Now let assume you override the classpath variable at the System level and it says Classpath=ojdbc14.jar

Now if you run the class from the build folder : java com.wickedlysmart.MyClass

Java wll not search for the class file in the current folder(By default java or javac will look into the current folder if the classpath is not overriden anywhere either at system level or at command level), it will search only in the classpath given.

So you have to tell java to include current folder in the classpath too

java -cp . com.wickedlysmart.MyClass

If you go to the wickedlysmart folder and execute java MyClass

Java will fail to find your class because there is no such a class called MyClass,being put in a package now your classname is com.wickedlysmart.MyClass

This link gives more details : webpage
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!