Week 90 — What happens when running a Java program with `java -jar`?

Question of the Week #90
What happens when running a Java program with java -jar?
4 Replies
0x150
0x1504mo ago
The -jar option/argument is meant to tell JRE to process inside the archive file denoted after the -jar, usually with extension .jar . Then, Java (JRE) internally unarchive the .jar file and read the META information which points to what the class name that contains the main entry point to application (the one that have public static void main(String[]) method, along with required (if any) classpath.
Submission from .brutallus
0x150
0x1504mo ago
You tell the compiler to run the jar code in the file. if you only do java it will just use the system java version and debugs informations/versionnumber and stuff.
Submission from waifu.janna
dan1st
dan1st2mo ago
0x150
0x1502mo ago
When running the java command, it first parses the arguments passed to it and starts a JVM that would later execute the application. In order to run the program, the JVM takes the argument passed after java -jar (the name of the JAR file to run), and loads the file with that name as a zip file. In the zip file, it looks for a META-INF/MANIFEST.MF entry where it looks up the (compiled) main class. Then, it resolves the main class in the opened JAR file and loads that class as well as verifies it meaning that the JVM ensures that the class would not break the JVM in any way or have invalid instructions. Once the main class is loaded, the JVM runs the static initializer of that class and runs the main method. If the main class (or any other class) refers to other classes, these classes are also loaded, verified and initialized before they are used. If a referenced class cannot be found or the static initializer throws an exception, attempting to access that class throws a NoClassDefFoundError (except accessing it via reflection which would throw a ClassNotFoundException). If verification fails (which can happen if the class file was modified after compilation or if incompatible class files are used together, e.g. when updating a dependency without recompiling the dependent), a VerifyError is thrown. Initially, the JVM runs Java code in the interpreter which either translates each bytecode instruction (or combination of bytecode instructions) to machine code using predefined templates or it reads the instructions and executes them instruction by instruction. When some code is used sufficiently often, the JIT optimizes that code and compiles it to machine code. When this is done, the used code is replaced by the machine code. In case of assumptions made during the compilations are violated or if certain diagnostic tools like a debugger are used, the JIT may deoptimize compiled code which is then run by the interpreter again.

Did you find this page helpful?