Demystifying Java Classpaths

by Clay Moore on December 15, 2009

in Computer Language,Computers,Java

This is a question that comes up a lot in my Java classes. Basically the students are a little bemused by the Classpath and what it is and how to use it. So My explanation is after the break

Java Classpath is the way that Java determines how to find classes to load. Java does not link objects and classes during compile time like C and c++ do. Instead there is something called the class loader that loads the class when called for in the code.

In order for the JVM to do this it must be able to find the location of the classes, be they in jars or naked classes. The JVM uses the classpath environment variable to limit it’s search for classes. It does not have to deal with the classes that are a part of the standard JRE. Those classes are already in it’s classpath. It’s the new Classes or APIs that your company may have purchased, or downloaded. You could put your jars or classes in the jre_home/lib/ext directory, or you have to put together a Classpath environment variable.

If you start putting together a Classpath environment variable you may wish to include the . in it. The period(.) means look int he current working directory, which is usually the directory that the executing(main method) class was located. The class path is not the path. The path is where executables are located. Java classes may not be executables in the normal sense of the word.

You can overrride a class path environment variable by using the classpath or -cp command line option when executing you program from the command line. In fact this is probably the best way to invoke your programs if they use custom classes or jar files. The last option is to package the new classes or jars with the application in the application’s jar file. As long as the (.) is int he classpath the JVM will search the running jar for any Java classes to load.

These are the techniques to ensure that Java will find your supporting libraries for you runing applications.

Share

Related posts:

  1. 3 Things to remember about Java
  2. New Java For Mac update
  3. Instructor in a Box Classes
  4. This past week
  5. This week in the life of this TechWarrior – 12/19/2009

Leave a Comment

*

{ 1 trackback }

Previous post:

Next post:

<