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 “helloworld.java”.

public class helloworld{
        public static void main(String[] args){
                System.out.println("Hello!");
        }
}

Compile & Run

$ javac helloworld.java
$ java helloworld

Output

Hello!

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 helloworld.java.

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

Compile & Run

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

Output:

Abcd

For Windows, “:” should be replaced with “;”.

4 thoughts on “Compile and Run Java in Command Line with External Jars”

  1. Though it is old post, this might help others.

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

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

Leave a Comment