The Wayback Machine - http://web.archive.org/web/20240620231508/https://www.geeksforgeeks.org/compilation-execution-java-program/
Open In App

Compilation and Execution of a Java Program

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Java, being a platform-independent programming language, doesn’t work on the one-step compilation. Instead, it involves a two-step execution, first through an OS-independent compiler; and second, in a virtual machine (JVM) which is custom-built for every operating system. 

The two principal stages are explained below:

Principle 1: Compilation

First, the source ‘.java’ file is passed through the compiler, which then encodes the source code into a machine-independent encoding, known as Bytecode. The content of each class contained in the source file is stored in a separate ‘.class’ file. While converting the source code into the bytecode, the compiler follows the following steps:

Step 1: Parse: Reads a set of *.java source files and maps the resulting token sequence into AST (Abstract Syntax Tree)-Nodes.

Step 2: Enter: Enters symbols for the definitions into the symbol table.

Step 3: Process annotations: If Requested, processes annotations found in the specified compilation units.

Step 4: Attribute: Attributes the Syntax trees. This step includes name resolution, type checking and constant folding.

Step 5: Flow: Performs dataflow analysis on the trees from the previous step. This includes checks for assignments and reachability.

Step 6: Desugar: Rewrites the AST and translates away some syntactic sugar.

Step 7: Generate: Generates ‘.Class’ files. 

https://www.youtube.com/watch?v=0f-Sx81bIWQ

Principle 2: Execution

The class files generated by the compiler are independent of the machine or the OS, which allows them to be run on any system. To run, the main class file (the class that contains the method main) is passed to the JVM and then goes through three main stages before the final machine code is executed. These stages are:
These states do include:

  1. ClassLoader
  2. Bytecode Verifier
  3. Just-In-Time Compiler

Let us discuss all 3 stages. 

Stage 1: Class Loader

The main class is loaded into the memory bypassing its ‘.class’ file to the JVM, through invoking the latter. All the other classes referenced in the program are loaded through the class loader.
A class loader, itself an object, creates a flat namespace of class bodies that are referenced by a string name. The method definition is provided below illustration as follows:

Illustration:

// loadClass function prototype

Class r = loadClass(String className, boolean resolveIt);

// className: name of the class to be loaded
// resolveIt: flag to decide whether any referenced class should be loaded or not.

There are two types of class loaders

  • primordial
  • non-primordial

The primordial class loader is embedded into all the JVMs and is the default class loader. A non-primordial class loader is a user-defined class loader, which can be coded in order to customize the class-loading process. Non-primordial class loader, if defined, is preferred over the default one, to load classes. 

Stage 2: Bytecode Verifier

After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode verifier, whose job is to check that the instructions don’t perform damaging actions. The following are some of the checks carried out: 

  • Variables are initialized before they are used.
  • Method calls match the types of object references.
  • Rules for accessing private data and methods are not violated.
  • Local variable accesses fall within the runtime stack.
  • The run-time stack does not overflow.
  • If any of the above checks fail, the verifier doesn’t allow the class to be loaded.

Stage 3: Just-In-Time Compiler

This is the final stage encountered by the java program, and its job is to convert the loaded bytecode into machine code. When using a JIT compiler, the hardware can execute the native code, as opposed to having the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a relatively lengthy translation process. This can lead to performance gains in the execution speed unless methods are executed less frequently.

Image

The process can be well-illustrated by the following diagram given above as follows from which we landed up to the conclusion.

Conclusion: Due to the two-step execution process described above, a java program is independent of the target operating system. However, because of the same, the execution time is way more than a similar program written in a compiled platform-dependent program.

Implementation:

Consider simple printing program is written somewhere on the local directory in a machine.

Java




// Java Program to Illustrate Compilation and Execution
// Stages
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Print command
        System.out.print("Welcome to Geeks");
    }
}


Output

Welcome to Geeks

Let us understand the real compilation and execution process.

Step 1: Let us create a file writing simple printing code in a text file and saving it with “.java” extension.

Image

Step 2: Open the terminal(here we are using macOS)and go to the Desktop directory using the below command as follows.

 cd /Users/mayanksolanki/GFG.java

Step 3: Let us try to compile our program with the below command

javac GFG.java

Step 4: Lastly run it with the below command as follows:

java GFG 

Note:  GFG.class file is created after the third step which means that now our entire code in the java programming language is secure encrypted as it contains only binary. In step 4 we are running that file. Refer to the below media for ease of understanding.

Image



Similar Reads

Class Loading and Static Blocks Execution Using Static Modifier in Java
Static is a keyword which when attached to the method, variable, Block makes it Class method, class variable, and class Block. You can call a static variable/method using ClassName. JVM executes the static block at “CLASS LOADING TIME” Execution Order: There is an order in which static block/method/variable gets initialized. Static BlockStatic Vari
3 min read
Order of execution of Initialization blocks and Constructors in Java
Prerequisite : Static blocks, Initializer block, Constructor In a Java program, operations can be performed on methods, constructors and initialization blocks. Instance Initialization Blocks : IIB are used to initialize instance variables. IIBs are executed before constructors. They run each time when object of the class is created. Initializer blo
4 min read
Execution Engine in Java
Java virtual machine or JVM can be visualized as a virtual machine residing in the computer that provides an environment for the code to get executed. Java Runtime Environment or JRE is an implementation of the JVM. In order to execute the code, an execution engine is used. In this article, let's understand the execution engine and different compon
3 min read
Spring Batch - Job Scheduling and Job Execution
Spring Batch is a framework for building robust and scalable batch-processing applications in Java. It provides features for job scheduling and job execution, making it well-suited for tasks such as data extraction, transformation, and loading (ETL), report generation, and more. In this explanation, I'll walk you through the process of scheduling a
3 min read
Servlet - Flow Of Execution
Servlets provide a way to communicate with client requests and generate dynamic responses based on the request-response programming model. Servlets can respond to any type of request but in most cases, these are used in web applications hosted by web servers. For these applications, Java Servlets define HTTP - specific servlet classes. For writing
9 min read
JUnit Test Execution For a MongoDB Collection using Maven
MongoDB is a NoSQL versatile database and it is widely used in software industries. Wherever there is no strict relational database relationship is necessary and also if there are chances of fetching the document often, it is always good to go with MongoDB. In this article, let us see the ways of Connecting to MongoDB,Creating collection,Inserting
4 min read
JUnit 5 – Conditional Test Execution
JUnit is one of the popular unit testing frameworks for Java projects. JUnit 5 is the latest version provided by the JUnit team launched with the aim of supporting the latest Java features and also providing notable advanced features to its predecessor JUnit 4. In this article, we will discuss one of the features called Conditional Test Execution i
8 min read
JUnit 5 – Test Execution Order
In JUnit 5, the Test execution order is not in the order by default. Every Test is randomly executed one after the other. There is no compulsion that the test which is on top will be executed first and the test which is in bottom will be executed last. So, the order of execution of test cases is unpredictable. JUnit 5 is now giving the programmer t
4 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Program to Extract Content from a Java's .class File
In this article, we are going to extract the contents of the Java class file using the Apache Tika library. Apache Tika is used for document type detection and content extraction from various file formats. It uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing
2 min read
Article Tags :
Practice Tags :