DEV Community

Cover image for What Happens When We Run a .java Code?
Leetcode
Leetcode

Posted on • Updated on

What Happens When We Run a .java Code?

Image 1

Java is a popular programming language that is used to create a wide variety of applications, from simple websites to complex enterprise software. When you run a .java code, a series of events takes place in order to execute the program.

The first step is to compile the code. The Java compiler, javac, converts the .java code into a .class file. The .class file is a binary file that contains the bytecode for the program.

Image 2

The next step is to load the .class file into the Java Virtual Machine (JVM). The JVM is an interpreter that executes the bytecode. The JVM is responsible for managing the memory, threads, and other resources that are needed to run the program.

Image 3

Once the .class file is loaded into the JVM, the main method of the program is executed. The main method is the starting point for all Java programs.

Image 4

The JVM then executes the bytecode instructions in the .class file one at a time. Each bytecode instruction performs a specific operation, such as adding two numbers, printing a message to the console, or creating a new object.

Image 5

The JVM continues to execute the bytecode instructions until the program terminates. When the program terminates, the JVM releases the memory and other resources that were used by the program.

Here is an example of a simple Java program and the output when it is run:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}
Enter fullscreen mode Exit fullscreen mode

output:

Hello, world!
Enter fullscreen mode Exit fullscreen mode

This program defines a class called HelloWorld. The main method of the class prints the message "Hello, world!" to the console. When the program is run, the JVM loads the .class file into memory and executes the main method. The main method prints the message "Hello, world!" to the console and then terminates the program.

Image 6

Here are some additional things to keep in mind when running a .java code:

The javac compiler must be installed on the system in order to compile the .java code.
The JVM must also be installed on the system in order to run the .class file.
The .class file must be in the same directory as the Java program that is calling it.
The Java program must have the correct permissions in order to run the .class file.

If you have any questions, please feel free to comment! I will explain in a very simple way.

Top comments (0)