Urgent.News

600+ sources. One page. See who else covered it.

Editions

Tech

What Really Happens When You Run a Java Program? A Deep Dive from .java to JVM Execution ❓️❓️

What Really Happens When You Run a Java Program? A Deep Dive from ".java" to JVM Execution When we write a Java program, it looks deceptively simple: public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } } We save the file, run: javac Main.java java Main and get: Hello, World! But what actually happens between these two commands? Java doesn't directly…

When launching a Java program, the apparent simplicity of typing "java Main" conceals a complex, multi-stage process. Begin with a human-readable ".java" file, such as:

public class Main {

public static void main(String[] args) {

int a = 10;

int b = 20;

System.out.println(a + b);

}

}

Save this file as "Main.java". The computer cannot execute this text directly. Compiling the Code With the command "javac Main.java", the Java compiler (javac) begins transforming the .java file into bytecode. Rather than producing native machine code unique to a specific operating system, Java converts the source code into an intermediate form called bytecode. This bytecode is stored in a file with a ".class" extension, for example, "Main.class". The bytecode appears as instructions like:

iload iadd invokevirtual return

These are not directly executable by the computer's CPU. The Role of the JVM The Java Virtual Machine (JVM) takes over, enabling the program to run across different platforms. Rather than executing the bytecode on its own, the JVM employs several key components:

1. Class Loader: Finds and loads the .class file into the JVM's memory. 2. Bytecode Verification: Ensures the bytecode adheres to JVM constraints, contributing to Java's runtime safety. 3. Runtime Memory Management: Manages several areas including the Heap (for objects) and Stack (for method calls). 4. Execution Engine: Consists of an Interpreter and JIT Compiler. - The Interpreter reads bytecode sequentially, executing it. - JIT Compiler optimizes frequently executed sections of bytecode into native machine code for improved performance. The Execution Flow When launching the program with "java Main", the JVM follows:

1. Loads the "Main" class. 2. Verifies the bytecode. 3. Allocates runtime memory. 4. Executes the bytecode, either via the Interpreter or JIT Compiler. 5. Outputs "Hello, World!" to the console. This intricate journey—from source code to running application—demonstrates Java's unique approach of "Write Once, Run Anywhere," blending the benefits of high-level programming with platform-independent execution.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Sunday 9 August →