How to set classpath in Java

In three ways we can set Class path for an application.

  1. You can use java command ‘–classpath’ option
  2. You can set in system environment variables
  3. You can also add required jars under installed jdk’s ext folder.

What is a classpath setting?

java and javac are called SDK tools. The classpath tells to java and javac commands where to find third party classes and also user defined class files -- that means you are using some third party classes in your application which are not part of java platform. Those third party classes jar path need to be set for javac and java commands in order to compile and run your application, this can done by setting classpath argument for java and javac commands. java and javac SDK tools will look for third party classes in current working directory.

Note: First option is always preferred way compare to second option, because by setting classpath in environment will be applicable for all applications running in the system, so some times it affects the other applications.

For example application1 is using oracle 10g and application2 is using oracle 9i. For Database connection we need to set proper database jar file in classpath, so assume that application1 is using ojdbc14.jar and application2 is using oracleThindriver.jar. Now if you set oracleThindriver.jar in environment variables it might affect application1 while creating connection for database. Instead if you use first option for setting classpath then you have to set separate for each application at runtime.

How to set classpath while running java command:

Assume ‘’ is the package structure and it is located in D:/JavaExample.
Assume it has 3 class files DataBaseConnection.class, DataBaseManager.class, MainClass.class.
In order to run the application either corresponding database driver should exist in environment variables (not preferred way) or set database driver jar in the classpath at runtime.
java tool has –cp options as well which is abbreviation for –classpath.

Example: D:/JavaExample> java –cp .; “D:\Oracle\product\10.1.0\Client_1\jdbc\lib\ojdbc14.jar ; D:\Oracle\product\10.1.0\Client_1\jdbc\lib\classes12.jar” MainClass

OR alternately;
D:/JavaExample> java –classpath; “D:\Oracle\product\10.1.0\Client_1\jdbc\lib\ojdbc14.jar ; D:\Oracle\product\10.1.0\Client_1\jdbc\lib\classes12.jar” MainClass

When application runs, the JVM will set class path to find any other classes defined in the ojdbc14.jar and classes12.jar that are used by the MainClass class.

In above example java interpreter will look for needed classes in an order which you have defined. If required class is not found in ojdbc14.jar then interpreter look in the classes12.jar.

Relative topic:

Set environmental variables in java
HTML Comment Box is loading comments...