Skip to content

Commit f110d7d

Browse files
committed
docs(JAR): explain what a JAR file is with examples
What - Documented **JAR (Java ARchive)** files as packaged archives for Java applications and libraries. - Key features: - File extension `.jar`. - Bundles multiple `.class` files, resources (images, configs), and metadata into a single archive. - Built on ZIP format with a special `META-INF/MANIFEST.MF` file. - Used for distribution, deployment, and execution of Java programs. - Can be executable (with a Main-Class entry) or non-executable (used as a library). Why - Simplifies distribution by combining many class files/resources into one file. - Enables reusability of code as libraries (e.g., external dependencies). - Supports portability across platforms with the JVM. - Provides versioning and metadata for deployment tools. How - **Creating a JAR file:** 1. Compile Java program: ``` javac Main.java ``` 2. Package into JAR: ``` jar cfe MyApp.jar Main Main.class ``` - `c` → create archive. - `f` → output to file. - `e` → specify entry point (Main-Class). java -jar MyApp.jar jar tf MyApp.jar Lists files inside archive. Examples 1. **Hello World executable JAR** - `Main.java`: ```java public class Main { public static void main(String[] args) { System.out.println("Hello, World from JAR!"); } } ``` - Compile and package: ``` javac Main.java jar cfe Hello.jar Main Main.class java -jar Hello.jar ``` - Output: ``` Hello, World from JAR! ``` 2. **Library JAR** - Create utility classes, bundle into `Utils.jar`. - Add to another project’s classpath: ``` java -cp .;Utils.jar MyApp ``` Logic - Inputs: compiled `.class` files and resources. - Outputs: compressed `.jar` archive. - Flow: 1. Java compiler generates `.class`. 2. jar tool packages classes/resources into `.jar`. 3. JVM runs `java -jar` if Main-Class is defined. - Edge cases: - Without Main-Class in manifest, `java -jar` fails. - Paths with spaces must be quoted. - Complexity / performance: - Simple ZIP compression; overhead minimal. - Concurrency / thread-safety: - Multiple JARs can be used simultaneously on the classpath. Real-life applications - Delivering Java applications as single executable files. - Packaging reusable libraries (e.g., `gson.jar`, `mysql-connector.jar`). - Used in build tools (Maven, Gradle) for dependency management. - Required in Java EE/ Jakarta EE deployments (WAR/EAR contain JARs internally). Notes - Executable JAR requires `META-INF/MANIFEST.MF` with Main-Class specified. - Non-executable JARs serve as libraries only, added to classpath. - JARs can be signed for integrity and security. - Still widely used even with newer formats (like JMOD in Java 9+). Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent d6b3857 commit f110d7d

File tree

1 file changed

+196
-0
lines changed

1 file changed

+196
-0
lines changed

Tips And Tricks/Jar File Java.txt

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
What is a JAR file?
2+
3+
A JAR (Java ARchive) is a package file format (based on ZIP) used to bundle Java classes, resources, and
4+
metadata into a single file.
5+
6+
A JAR makes it easy to distribute Java libraries, applications, and resources as one portable unit.
7+
8+
Key characteristics:
9+
• ZIP-based archive (.jar).
10+
• Contains compiled .class files, resource files (properties, images), and an optional META-INF/MANIFEST.MF.
11+
• Can be executed (if it contains a Main-Class entry in the manifest) or used as a library on the classpath.
12+
13+
Why JAR files are important
14+
• Distribution — package everything needed (classes + resources) into one file for easy sharing and deployment.
15+
• Reproducibility — stable artifact that can be versioned and archived.
16+
• Classpath management — simplifies dependency handling (one file instead of many loose class files).
17+
• Security & Integrity — supports signing (JAR signing) and manifest metadata.
18+
• Performance — fewer filesystem entries and easier I/O handling; commonly used by class loaders.
19+
• Tooling compatibility — all build tools (Maven, Gradle, Ant), application servers, and the JVM understand JARs.
20+
21+
Basic JAR layout
22+
23+
A typical JAR structure:
24+
25+
myapp.jar
26+
├─ META-INF/
27+
│ ├─ MANIFEST.MF <-- manifest file (metadata)
28+
│ └─ (optional signatures, other metadata)
29+
├─ com/example/App.class
30+
├─ com/example/Utils.class
31+
├─ config/app.properties
32+
└─ images/logo.png
33+
34+
Important manifest entries (META-INF/MANIFEST.MF)
35+
36+
A manifest is a small text file containing key-value pairs. Common entries:
37+
• Manifest-Version: 1.0
38+
• Main-Class: com.example.App — makes the jar executable (java -jar myapp.jar).
39+
• Class-Path: lib/foo.jar lib/bar.jar — reference other jars (space separated) relative to the jar.
40+
• Implementation-Version, Implementation-Title, Built-By, Created-By — useful metadata.
41+
• Sealed: true (package sealing), Multi-Release: true (multi-release JARs).
42+
43+
Creating and running JARs — basic commands
44+
45+
Using the JDK jar tool (manual / small projects):
46+
1. Create a JAR (pack classes and resources):
47+
48+
jar cf myapp.jar -C out/classes .
49+
50+
c = create, f = specify filename, -C out/classes . = change dir to compiled classes.
51+
2. Create a JAR with an explicit manifest (executable):
52+
53+
• Create manifest.txt:
54+
55+
Manifest-Version: 1.0
56+
Main-Class: com.example.Main
57+
58+
• Build jar:
59+
60+
jar cfm myapp.jar manifest.txt -C out/classes .
61+
62+
m = include manifest file.
63+
3. Run an executable JAR:
64+
65+
java -jar myapp.jar
66+
67+
4. List contents of a jar:
68+
69+
jar tf myapp.jar
70+
71+
5. Extract a jar:
72+
73+
jar xf myapp.jar
74+
75+
Using build tools (recommended for real projects)
76+
• Maven: mvn package builds a JAR (and can configure an executable “fat” JAR via maven-shade-plugin or
77+
spring-boot-maven-plugin).
78+
• Gradle: gradle jar for plain jar, or gradle shadowJar (with Shadow plugin) to create a fat/uber JAR.
79+
• These tools handle dependency resolution, manifest generation, resource filtering, and reproducible builds.
80+
81+
Types of JARs
82+
• Library JAR — contains classes/resources for use by other apps (not necessarily executable).
83+
• Executable JAR — contains Main-Class in manifest; runnable with java -jar.
84+
• Fat / Uber JAR — bundles project classes plus all dependencies in one large JAR
85+
(useful for single-file deployment). Tools: Maven Shade, Gradle Shadow.
86+
• Modular JAR — contains module-info.class and follows Java Platform Module System (JPMS).
87+
Used with java --module-path.
88+
• Multi-Release JAR (MRJAR) — allows including version-specific class files under META-INF/versions/ for use
89+
on different Java versions.
90+
• Signed JAR — signed with jarsigner for authenticity/integrity.
91+
92+
Classpath & class loading
93+
• A JAR becomes usable by adding it to the classpath: java -cp mylib.jar;myapp.jar com.example.Main.
94+
• java -jar ignores the -cp option and uses the manifest’s Class-Path plus the jar itself.
95+
• Class loaders load classes from JARs; order matters. Conflicting classes across jars cause “classpath hell”.
96+
97+
Executable JAR gotchas
98+
• java -jar uses only the manifest classpath and ignores -cp — if you need additional jars,
99+
either set Class-Path in the manifest or use -cp with a main class.
100+
• Fat jars make deployment simpler but can cause duplicate resource/class conflicts —
101+
use shading to relocate packages if necessary.
102+
103+
Jar signing & security
104+
• Sign a JAR using jarsigner (provides origin & integrity verification).
105+
• Signed JARs are required for applets or for some secure environments.
106+
• Signing adds .SF, .RSA/.DSA files into META-INF/.
107+
108+
Modular jars & JPMS
109+
• Introduced in Java 9. A modular jar contains a module-info.class.
110+
• Run with module path: java --module-path mods -m com.example/com.example.Main.
111+
• Modules help strong encapsulation and reliable configuration; however many existing libraries are still
112+
non-modular.
113+
114+
Best practices
115+
• Use Maven/Gradle for build and dependency management — they produce consistent JARs and handle manifests.
116+
• Prefer library jars (small, focused) for reuse. Use fat jars for easy deployment where appropriate
117+
(microservices, small utilities).
118+
• Keep the manifest minimal and correct; set Main-Class only when building an executable jar.
119+
• Use semantic versioning in jar filenames/dependency coordinates.
120+
• Avoid mixing many unrelated dependencies into a single fat jar unless necessary.
121+
• If using fat jars, use shading/relocation to avoid dependency conflicts.
122+
• Test your jar locally before releasing (verify java -jar, classpath resolution).
123+
• Sign only when you need to verify publisher identity; manage keys carefully.
124+
125+
Common issues & troubleshooting
126+
• NoClassDefFoundError or ClassNotFoundException: missing dependency on classpath or improper manifest Class-Path.
127+
• Could not find or load main class: wrong Main-Class in manifest or wrong package/class name.
128+
• Duplicate classes/resource conflicts in fat jars — use shading or exclude duplicates.
129+
• Incorrect manifest format: manifest lines must end with \r\n/\n and a blank line at the end;
130+
long values are wrapped using continued-line syntax.
131+
• java -jar ignores environment CLASSPATH for security/consistency (older versions behave differently).
132+
• Permission issues on Windows/macOS when executing jar — ensure java is on PATH and file permissions allow reading.
133+
134+
Useful commands & tools
135+
• jar (JDK): cf, tf, xf, uf, cfm etc.
136+
• jarsigner (JDK): sign/verify jars.
137+
• jdeps (JDK): dependency analysis and module detection.
138+
• jlink (JDK): create custom runtime images (smaller, runtime+modules).
139+
• unzip / zip — you can open and inspect jar like any zip file.
140+
• Build tools: Maven, Gradle, Ant.
141+
• Plugins: Maven Shade, Gradle Shadow for fat JARs.
142+
143+
Examples (practical)
144+
1. Create an executable jar from compiled classes:
145+
146+
# assume classes in out/production/myapp
147+
echo "Manifest-Version: 1.0" > manifest.txt
148+
echo "Main-Class: com.example.Main" >> manifest.txt
149+
jar cfm myapp.jar manifest.txt -C out/production/myapp .
150+
java -jar myapp.jar
151+
152+
2. Create a fat jar with Maven (pom.xml plugin snippet, conceptual):
153+
154+
<plugin>
155+
<groupId>org.apache.maven.plugins</groupId>
156+
<artifactId>maven-shade-plugin</artifactId>
157+
<version>3.2.4</version>
158+
<executions><execution><phase>package</phase><goals><goal>shade</goal></goals></execution></executions>
159+
</plugin>
160+
161+
3. Inspect dependencies:
162+
163+
jdeps --multi-release 9 -s myapp.jar
164+
165+
JAR vs WAR vs EAR
166+
• JAR — general Java archive for libraries and standalone apps.
167+
• WAR — Web Application Archive, used for web apps (Servlets), deployable to servlet containers
168+
(Tomcat); has WEB-INF/.
169+
• EAR — Enterprise Archive for Java EE applications; bundles EJBs, WARs, libraries.
170+
171+
Performance & packaging notes
172+
• Multiple small jars increase filesystem overhead; a single jar can be simpler but less modular.
173+
• Class loader performance and startup time can be affected by the number of jars.
174+
• Using jlink to produce runtime images can drastically reduce deployment size when using modules.
175+
176+
Advanced topics (brief)
177+
• Multi-release JARs: provide version-specific implementations under META-INF/versions/.
178+
• Class-Path tricks: manifest Class-Path can reference external jars (relative paths).
179+
• Jar sealing: mark packages as sealed so all classes for a package come from the same jar.
180+
• Signed jars & Certificate Management: manage keystores, rotate keys, and verify signatures.
181+
182+
Quick Checklist for Building a Reliable JAR
183+
• Use a build tool (Maven/Gradle/Ant).
184+
• Include only needed dependencies; prefer modular jar layout where practical.
185+
• Define Main-Class if jar should be executable.
186+
• Test run with java -jar and via classpath usage.
187+
• If producing a fat jar, handle duplicate packages (use shading).
188+
• Optionally sign jar if distribution requires authenticity.
189+
• Add semantic version to artifact coordinates/filename and include build metadata in MANIFEST.MF.
190+
191+
Recommended further reading / next steps
192+
• Read the JDK jar tool docs and jlink docs.
193+
• Learn how your build tool (Maven/Gradle) creates jars and how to configure plugins (shade, assembly).
194+
• Experiment with modular jars and module-info.java if you target Java 9+ and want strong encapsulation.
195+
196+

0 commit comments

Comments
 (0)