How to Create and Use JAR Files in Java - Quiz
Total: 5 questions
1. What is a JAR file in Java?
What is a JAR file in Java?
JAR (Java ARchive) is an archive file in the ZIP format that bundles many .class files, resources (images, configuration files) and metadata (the MANIFEST.MF file) into a single file with the .jar extension. It is used to distribute and deploy Java applications and libraries as one convenient unit.
2. How do you create a JAR file from compiled classes?
How do you create a JAR file from compiled classes?
Use the jar tool: jar -cf MyJar.jar <files/directories>. The c flag means create, and f specifies the output file name. For example, jar -cf MyJar.jar myApp packs the myApp directory with all its classes into MyJar.jar, preserving the package directory structure inside the archive.
3. What is MANIFEST.MF and what does the Main-Class attribute do?
What is MANIFEST.MF and what does the Main-Class attribute do?
MANIFEST.MF is a special metadata file stored in the META-INF directory inside every JAR. The Main-Class attribute in the manifest specifies the fully qualified name of the class containing the main method that runs when you execute java -jar. Without a Main-Class entry, the JAR cannot be launched with java -jar.
4. How do you run an executable JAR file?
How do you run an executable JAR file?
Run it with java -jar app.jar. The JVM reads the Main-Class attribute from the manifest and invokes that class's main method. Note that when you use -jar, the CLASSPATH environment variable and any -classpath option are ignored — the classpath is defined entirely by the JAR's manifest (via the Class-Path attribute).
5. How do you add a JAR file to the classpath when compiling and running your code?
How do you add a JAR file to the classpath when compiling and running your code?
Use the -classpath (or short -cp) option: javac -classpath MyJar.jar MyClass.java and java -classpath .;MyJar.jar MyClass. The path separator is a semicolon (;) on Windows and a colon (:) on Linux/macOS. The dot (.) stands for the current directory, so include it if your own classes live there.