Back to Blog

How Java Works: Source Code, Compilation, Bytecode and Execution

When we write a Java program, save it as a .java file, and click the Run button in an IDE, the output appears almost instantly.

But what actually happens between writing the code and seeing the result?

How does a computer understand Java? How does human-readable source code become something a machine can execute? And why can the same Java application run on Windows, Linux, and macOS?

To understand Java properly, we need to look beyond its syntax and explore the journey of a program from source code to execution.

This journey involves four fundamental stages:

  1. Writing source code.
  2. Compiling source code.
  3. Generating bytecode.
  4. Executing bytecode.

Let's understand each stage.

1. Source Code: Where Everything Begins

Source code is the human-readable representation of instructions written in a programming language.

Consider a simple Java program:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }

}

We save this program in a file named:

HelloWorld.java

At this stage, we have only written instructions. The computer has not executed them yet.

Java source code follows a defined syntax and structure. It contains elements such as:

  • Classes
  • Methods
  • Variables
  • Statements
  • Expressions
  • Objects

A Java compiler understands these language rules and checks whether our program follows them.

But before that happens, let's understand the role of compilation.

2. Compilation: Translating Human-Readable Code

A computer's processor does not directly understand Java source code.

Processors execute machine instructions specific to their architecture.

Therefore, Java source code needs to be translated into an executable representation.

This process is called compilation.

Java provides a compiler called javac, which is included in the Java Development Kit (JDK).

We compile our program using:

javac HelloWorld.java

During compilation, the Java compiler performs several operations:

  • Checks Java syntax.
  • Performs type checking.
  • Validates language rules.
  • Resolves references to required types.
  • Generates bytecode when compilation succeeds.

If the source code contains compilation errors, the compiler reports them instead of producing the expected class file.

For example:

int number = "Hello";

This statement is invalid because we are trying to assign a String value to an integer variable.

The compiler identifies this type mismatch before the program executes.

Successful compilation generates:

HelloWorld.class

But what exactly is inside this file?

3. Bytecode: The Intermediate Representation

The .class file contains something called Java bytecode.

Bytecode is an intermediate instruction format designed for execution by the Java Virtual Machine (JVM).

It is neither ordinary Java source code nor the native machine code of a particular processor.

This distinction is extremely important.

Instead of compiling Java source code directly into machine instructions for Windows, Linux, or macOS, Java compiles it into a common intermediate format.

The JVM on each platform is responsible for executing that format.

We can inspect the generated bytecode using the javap tool:

javap -c HelloWorld

The output will contain instructions similar to:

public class HelloWorld {
  public HelloWorld();
    Code:
       0: aload_0
       1: invokespecial #1
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: getstatic     #7
       3: ldc           #13
       5: invokevirtual #15
       8: return
}

These are bytecode instructions.

Some examples:

  • aload_0 - Loads a reference from a local variable.
  • getstatic - Reads a static field.
  • ldc - Loads a constant.
  • invokevirtual - Invokes an instance method.
  • return - Returns from a method.

We do not normally write these instructions ourselves. The compiler generates them.

Bytecode provides an abstraction between the Java programming language and the underlying hardware.

4. Execution: The JVM Takes Over

Once compilation is complete, we can execute our program:

java HelloWorld

The Java launcher starts the JVM, which loads and executes the required bytecode.

The JVM does not simply read the .class file and immediately execute everything. Several internal processes take place.

Step 1: Class Loading

The Class Loader loads the required classes into the JVM.

For example, when our program references HelloWorld, the JVM loads that class so it can be used during execution.

Classes can also be loaded dynamically when needed.

Step 2: Bytecode Verification

Before execution, the JVM verifies bytecode to check that it follows the required structural and safety rules.

This helps prevent malformed or invalid bytecode from being executed.

Step 3: Memory Allocation

The JVM manages runtime memory.

Objects and arrays are generally allocated in the heap, while method execution uses stack frames associated with individual threads.

The JVM also maintains other runtime structures required for class information and execution.

Step 4: Execution Engine

The execution engine executes the bytecode.

It primarily uses two approaches:

Interpreter

The interpreter executes bytecode instructions as the program runs.

This allows execution to begin without waiting for the entire application to be compiled into native machine code.

Just-In-Time (JIT) Compiler

The JIT compiler identifies frequently executed code and compiles suitable portions into native machine code.

This improves performance by allowing frequently executed operations to run more efficiently.

Modern JVMs use runtime profiling and optimization techniques to make intelligent decisions about compilation.

Step 5: Garbage Collection

During execution, Java applications create objects and allocate memory.

When objects are no longer reachable, the garbage collector can reclaim their memory.

This automatic memory management is one of the important features of the Java platform.

5. Understanding the Complete Journey

Let's bring everything together.

       JAVA SOURCE CODE
          HelloWorld.java
                |
                |
                v
        JAVA COMPILER
            javac
                |
                |
                v
          BYTECODE
         HelloWorld.class
                |
                |
                v
       JAVA VIRTUAL MACHINE
              JVM
                |
        -----------------
        |               |
        v               v
    Interpreter      JIT Compiler
        |               |
        |               |
        v               v
       EXECUTION OF JAVA APPLICATION
                |
                v
          PROGRAM OUTPUT
          Hello, World!

This is the fundamental lifecycle of a Java program.

One important detail: the interpreter and JIT compiler are not necessarily two completely separate execution stages. They work together as parts of the JVM's execution strategy.

6. Why Does Java Run on Different Operating Systems?

This brings us to one of Java's most important design principles:

Write Once, Run Anywhere (WORA).

Imagine writing and compiling a Java application on Windows.

The compiler generates bytecode in a .class file.

Now suppose we move that compiled application to a Linux machine.

Can it run?

Yes, provided a compatible JVM and the required dependencies are available.

Why?

Because the bytecode is not designed specifically for Windows or Linux.

Instead, each operating system has its own JVM implementation.

The architecture looks like this:

       JAVA APPLICATION
              |
              v
          BYTECODE
              |
       ----------------
       |       |      |
       v       v      v
     JVM     JVM     JVM
   Windows  Linux   macOS
       |       |      |
       v       v      v
    Windows  Linux   macOS
    Machine  Machine Machine

The JVM acts as an abstraction layer between Java bytecode and the underlying operating system and hardware.

This is why Java is considered platform-independent.

However, platform independence does not mean every Java application is automatically portable. Applications using native libraries, operating-system-specific features, or external dependencies may require additional configuration.

7. Is Java an Interpreted or Compiled Language?

This is a common question.

The answer is: Java uses both compilation and interpretation, along with Just-In-Time compilation.

Let's understand the distinction.

Approach How it works
Compiled languages Translate source code into another executable representation before execution
Interpreted execution Execute instructions through an interpreter at runtime
JIT compilation Compile selected code into native machine instructions during runtime

Java first compiles source code into bytecode.

The JVM then executes that bytecode using interpretation and JIT compilation.

Therefore, describing Java as only a compiled language or only an interpreted language does not fully explain how it works.

It combines both approaches.

8. What About IDEs Like IntelliJ IDEA and Eclipse?

When we work with Java in an IDE, we rarely execute compiler commands manually.

Tools such as IntelliJ IDEA and Eclipse simplify the development process.

They provide:

  • Code editors and syntax highlighting.
  • Compilation and error detection.
  • Debugging facilities.
  • Build tool integration.
  • Dependency management.
  • Application execution.

When we click Run, the IDE coordinates the necessary build and execution operations.

Underneath, the same fundamental Java compilation and execution mechanisms are involved.

The IDE does not replace the Java compiler or JVM. It provides a convenient interface for working with them.

9. A Practical Experiment

Let's verify everything ourselves.

First, check whether Java is installed:

java -version
javac -version

Create a file named Calculator.java:

public class Calculator {

    public static void main(String[] args) {

        int first = 10;
        int second = 20;

        int result = first + second;

        System.out.println("Result: " + result);
    }
}

Compile the program:

javac Calculator.java

Notice that a new file appears:

Calculator.class

Inspect the bytecode:

javap -c Calculator

Execute the program:

java Calculator

Expected output:

Result: 30

Try modifying the program, compiling it again, and inspecting the bytecode.

Observe how a small change in source code can produce different bytecode instructions.

This simple experiment demonstrates the complete journey from source code to execution.

Conclusion

Java's execution model is one of the reasons it became such an influential programming language.

Instead of directly translating source code into machine instructions for a specific operating system, Java introduces an intermediate representation called bytecode.

The JVM then provides the environment required to execute that bytecode.

Understanding this process gives us a foundation for exploring more advanced topics such as memory management, class loading, garbage collection, multithreading, and runtime optimization.

Before learning how to build enterprise applications with Spring, we should understand what happens underneath the Java code we write.