How to include jar files with java file and compile in command prompt
To compile and execute a Java file with JAR dependencies using the command prompt:
Compile:
Run:
Substitute jar1.jar
, jar2.jar
with your JAR files, MyClass
with your class name. Use :
instead of ;
on Unix/Linux. Classpath, denoted by -cp
, contains both external JARs and current directory .
.
The Classpath explained
Classpath is a Java Runtime Environment parameter that points out the location of user-defined classes and packages. It can be set using -cp
or -classpath
flag in javac
and java
commands, providing the road map for Java to find your classes.
Project structuring: Keep it clean
Maintain a clean project structure by keeping all your .java
files in one source directory, and all .jar
files in a separate lib
folder.
Bulk up on JARs
Manually specifying each JAR file can be tedious. Use the all-powerful *
wildcard to include all JARs in a directory:
Classpath hierarchy: It matters!
Order of JAR files matters as Java will load the first occurrence of a class. So, organize your classpath considering multiple versions of classes/packages present in your JARs.
Going Persistent: use environment variables
To maintain your JAR configurations across sessions, utilize the CLASSPATH
environment variable. It's like your backpack, always with you:
Avoid the pitfalls
Look out for common mistakes like excluding the current directory .
from classpath resulting in ClassNotFoundException
, mismatching order of JAR files causing NoClassDefFoundError
or using incorrect classpath separator for your OS.
Troubleshooting tips
If you encounter compilation errors, make sure your classpath points to the absolute stars (not literally!). Use absolute paths for clarity, validate JAR names and versions.
Running the race
Executing your Java file successfully indicates all dependencies are included. If you encounter runtime errors, reconnoiter your classpath to ensure runtime dependencies are included.
Environment variables: A big lever
Manipulating the CLASSPATH
environment variable is like wielding a magic wand: it allows you to control class loading and resolve dependencies in Java's runtime environment.
Was this article helpful?