How to Compile and Run Java Programs with External Libraries


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

If you use an IDE like Eclipse to develop your Java programs then using external libraries is pretty straight forward. You just need to add the JAR file to your project and then right click on it and add it to the build path, and the IDE will do the rest of the work for you.

If you are writing and running your programs from the command line, however, you’ll need to add the classpath manually.

Let’s suppose you want to use the Apache Lang library. First you need to download the tar file and extract it to the folder of your application. Then you can compile it like this:

javac -cp commons-lang3-3.2/commons-lang3-3.2.jar MyClass.java

And then run it like this:

java -cp .:commons-lang3-3.2/commons-lang3-3.2.jar MyClass

The tricky part is the .: before the jar file when running the program. Most people forget that, and if you do you’ll get an error.

Leave a Reply

Your email address will not be published. Required fields are marked *