Basics of Jar

A few years back, i was asked why a class in jar was not running as expected from command prompt. The answer was quite simple, the dependencies of the class are not available.

There is a common misconception that you create a jar and everything runs out of the box for you when you run the main class. Now what is the main class in the jar. Let me give you some introduction to jars:

a. Jar – Java archive. As the name says, it archives a set of java files.

b. Common Jar Operations

Operation Command
To create a JAR file jar cf jar-file input-file(s)
To view the contents of a JAR file jar tf jar-file
To extract the contents of a JAR file jar xf jar-file
To extract specific files from a JAR file jar xf jar-file archived-file(s)
To run an application packaged as a JAR file (requires the Main-class manifest header) java -jar app.jar

c. In general, a java file uses some or the other open source libraries e.g. log4j.jar, etc. Hence, when we create a jar, it is required that it is available in the class-path when we are creating the jar, so the class files can be created and then, they can be bundled. The same principles applies when you execute the jar file as well.

d. Every jar should have at-least one Main-class. Main-class is a class, which is a public class, with the public static void main(String[] args) method. This is the entry-point for all the classes in your jar. P.S. There can be more than one main class as well. In such a case, it is preferable not to have a main-class specified in the manifest.

e. A jar generally comes with a MAINFEST file. This is like meta-information about a jar. e.g.

Manifest-Version: 1.0
Main-Class: MyClass
Class-Path: MyUtils.jar
Created-By: 1.6.0 (Sun Microsystems Inc.)

Useful links:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s