In Java, the classpath tells the Java Virtual Machine where to look for user-defined classes and packages when running Java programs. The classpath is a parameter and can be set either on the command-line, or through an environment variable.
When executing Java programs, the JVM uses a method that is similar to classic dynamic-loading. That is, the JVM lazily finds and loads classes (meaning, the JVM loads a class only when it is first used). The classpath tells the JVM where to look for the files that define these classes, on the filesystem.
The JVM searches for and loads classes in the following order:
- Bootstrap classes: These are fundamental classes belonging to the Java platform. These are public classes that belong to the Java Class Library, and it also includes the private classes that are necessary for this library to function properly.
- Extension classes: These are packages that are in the extension directory of either the JRE or the JDK (usually in
jre/lib/ext/
). - User-defined packages and libraries: These are packages and libraries that are created by the user or that are being used by the user. These can include third-party libraries.
Packages from the JDK standard API and extension classes are accessible by default (the classpath doesn't need to be explicitly set to provide access to them). However, the path for all user-defined packages and libraries must be set. This can be done either via the command-line, an environment variable, or in the manifest file associated with the JAR file that contains the classes.