Compiling Java classes, building jar files and running the code

Compile and run single class

If you program consists of one single class, compile it:

$ javac

Run main method:

$ java -cp . Program

or even shorter:

$ java Program

Compiling and building jar

Build following directory structure:

+ - HelloWorld (project name - base directory (./))
+ - src (source files)
+ - abcd (package name - .java files)
+ - build
+ - classes (compiled files - .class files)

This is a test class:

package abcd;

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello Java world.");

Save this file in ./src/abcd as ''.


Now you can compile the java file:

$ javac -sourcepath ./src/ -d ./build/classes/ ./src/abcd/

This should create 'HelloWorld.class' file in ./build/classes directory


Run compiled class:

$ java -cp ./build/classes/ abcd.HelloWorld

This should result in displaying a message in console window:

Hello Java world.

Building jar


Before building jar, you must create Manifest file. This file tells the jar file in which class the main method is.

On unix you can simply create manifest file like this:

$ echo Main-Class: abcd.HelloWorld>myManifest

This creates new document called 'myManifest' with following line

Main-Class: abcd.HelloWorld

Build jar

$ jar cfm ./build/jar/HelloWorld.jar myManifest -C ./build/classes/ .

Don't forget white_space and . at the end of line. This means all the class files inside ./build/classes

Run jar

When jar is successfully created, you can run it with:

$ java -jar ./build/jar/HelloWorld.jar