Setting Classpath

Classpath is a parameter that helps Java compiler and JVM to look for user-defined class, interfaces, and packages. There are two ways by which you can set classpath-

  1. Setting classpath on the command line
  2. Setting classpath using environment variable

Before we learn how to set classpath, let's understand JVM, JRE, and JDK.

What is JDK?

JDK stands for Java Development Kit. It contains JRE plus all the tools required to compile and debug applications written in Java. It is designed for a particular platform, and this is the reason we have separate installers for each operating system.

What is JRE?

JRE stands for Java Runtime Environment. It is a subset of JDK. It does not contain tools required to develop Java programs. It is only used to run Java program. If you are having JRE installed on your computer, then you can execute programs written in Java. It contains JVM and all the necessary libraries required to run Java program.

What is JVM?

JVM stands for Java Virtual Machine. It converts bytecode into a form that machine can understand. Even though Java is platform independent, but JVM is platform dependent. It is responsible for performing following functions-

  • Loading, verification, and execution of code
  • Memory management
  • Garbage Collection
  • and others

How to set classpath on the command line

To set classpath on a command line, you can follow any one of the following methods-

  1. Run set classpath=path-of-user-defined-classes command on the command line. Example-
    set classpath=c:\myassignment
  2. Use classpath or cp command line option of javac and java command to specify the location of user-defined classes and interfaces. Example-
    javac -classpath c:\myassignment
    java -classpath c:\myassignment test

How to set classpath using environment variable

There is another way of setting classpath, all you need to do is just follow the below steps-

  1. Right click on My Computer or This PC icon and select Properties from the context menu.
  2. A window will appear, click on "Advanced system settings" present on the left side.
  3. A System Properties dialog box will appear. Click on Advanced tab and then click on Environment Variables.
  4. An Environment Variables dialog box will appear. Under System variables click on New button. A dialog box will appear. Type classpath in Variable name and the path of the directory in Variable value. Click on OK button to save all the changes.