Classpath is a parameter that defines the list of directories, JARs, and ZIPs where the Java Virtual Machine and compiler search for classes and resources when launching an application.
Background:
Since the inception of Java, there has been a need to organize the loading of a large number of classes that often reside in different directories. Classpath was designed to flexibly specify where to look for dependencies.
The Problem:
If classpath is misconfigured, the application will not find the necessary classes, leading to loading errors (e.g., ClassNotFoundException or NoClassDefFoundError).
The Solution:
Classpath can be set via the environment variable CLASSPATH, the command-line argument -cp, or -classpath. It is important to explicitly specify all directories and JAR files required for the application's functionality. Example of launching with classpath:
java -cp ".;lib/*" com.example.Main
Key features:
; (Windows) or : (Linux/macOS)lib/* — all JARs in the lib folderCan Java find classes by itself if they are not listed in the classpath?
No, Java does not automatically search for classes outside of the specified classpath. Each path must be explicitly mentioned or added during the build or launch step.
Does the order of paths in the classpath affect class loading?
Yes, if there are name collisions, the class found in the first specified path will be loaded first. Order is important to avoid version conflicts.
Can a new JAR be added to the classpath "on the fly" after the application is started?
No, the standard classpath mechanism is static after the JVM starts. Dynamically loading new classes requires special ClassLoaders.
A Java application is launched with the parameter -cp lib/mylib.jar, forgetting to add the folder with the test config. As a result, the application crashes with an error, even though the library seems to be present.
Pros:
Cons:
Using maven/gradle, which automatically constructs the classpath based on dependencies. Launching is done through a wrapper script.
Pros:
Cons: