JAR Files in Java

JAR(Java Archive File) file helps in bundling multiple Java program and its related files inside a single file.

It is similar to zip files but exclusively made for java program and its related files.

Why JAR files are used?

Sharing files easily

Imagine you created a program which includes 10 class files. You are sharing this in the internet, so that everyone can use this program or code.

The people who want to use your files, should download each class file separately and import in his program. To minimise the effort, we can bundle the class files and their related files into a single JAR file and share, so that the people can now download multiple files as a single file.

Efficient storage

It does compression similar to zip files which helps in using memory efficiently.

Increases security

You can sign the contents of jar file, so that one who recognizes signature can only use the files inside JAR.

Package Versioning

JAR file can store data on the files inside the JAR.

Package sealing

Imagine your are creating two classes, Data as private class and Access as public class inside a package myName in which class Data can only be accessed within its package i.e class Access can only access class Data.

You are bundling the above classes in a myJar1.jar file.

Your enemy creates another class Hack with the same package name myName as above and bundled the class inside a jar myJar2.jar.

If both the jar's are used in a project, class Hack might access private class Data because both the classes are under same package name. i.e Your enemy can access your class Data easily. To avoid this, package sealing is done to restrict access to other jars.