Compile and Run Java in Command Line with External Jars

The following example shows how to compile and run Java program in command line mode with external jars. It is developed under Linux.

1. Compile & Run Java Program Without External Jar

Let's create a simple hello world program "".

public class helloworld{
        public static void main(String[] args){

Compile & Run

$ javac
$ java helloworld



2. Compile & Run Java Program With External Jar

Now let's download a third-party library and use some method from the library. In this case, I downloaded apache.commons.lang from here, and use the StringUtils.capitalize() method. The jar file is downloaded to "jars" directory which is located the same with

import org.apache.commons.lang3.*;
public class helloworld{
        public static void main(String[] args){
                String x = "abcd";

Compile & Run

$ javac -cp ".:./jars/common.jar" 
$ java -cp ".:./jars/common.jar" helloworld



For Windows, ":" should be replaced with ";".

Category >> Basics >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. meet sharma on 2015-9-8

    now suppose if we want to add multiple jars,then what will be the solution ??

  2. Vishwas on 2016-10-17

    Though it is old post, this might help others.

    $ javac -cp “.:./jars/common.jar .:./jars/specific.jar”
    $ javac -cp jars/common.jar:jars/specific.jar

    For windows, semi colon should be used instead of colon.

  3. ccna training in pune on 2016-11-19

    Thanks for posting this useful content, Let me share this, . CCNA training in pune

Leave a comment