How Java Compiles & Runs & Source File Structure

โ˜• Java 21+ LTS ๐ŸŸข Chapter 3 of 47 ๐Ÿ“‚ Phase 1: Java Basics ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter:

Compilation Pipeline (javac to Bytecode to JVM) ยท Why Java is Compiled & Interpreted ยท Source File Structure Rules ยท Packages & Imports

Deep exploration of the complete Java compilation and execution pipeline: from source code (.java) to bytecode (.class) and native machine code, why Java is hybrid compiled/interpreted, and the mandatory architectural structure of Java source files.

1. The 2-Step Java Compilation & Execution Lifecycle

Java combines the speed of compiled languages with the flexibility of interpreted languages. Here is the step-by-step journey of your code:

+-----------------------------------------------------------------------------------+
|                        JAVA CODE EXECUTION PIPELINE                               |
+-----------------------------------------------------------------------------------+
|  [ Step 1: Human Source Code ]                                                    |
File: Main.java (Plain text readable code written by developer)
v
[ Step 2: Java Compiler (javac) ]
Command: javac Main.java
Action : Syntax validation, type checking, semantic analysis
| | v | | [ Step 3: Architecture-Neutral Bytecode ] |
File: Main.class (Compact, platform-agnostic bytecode instructions)
v
[ Step 4: Java Virtual Machine (JVM) ]
Command: java Main
Actions:
1. ClassLoader loads Main.class into memory
2. Bytecode Verifier checks security & memory safety
3. Execution Engine:
- Interpreter reads instructions immediately
- JIT Compiler compiles hot code paths into optimized machine code
| | v | | [ Step 5: Native Machine Execution ] | | Binary CPU instructions executed directly on Host CPU (Intel / AMD / ARM) | +-----------------------------------------------------------------------------------+

2. Why is Java both Compiled and Interpreted?

Lower-level languages (like C and C++) are Purely Compiled: they translate source code directly into CPU machine binaries. If the CPU changes, the binary breaks.

Higher-level scripting languages (like Python and JavaScript) are Purely Interpreted: the interpreter reads source code line-by-line during runtime, which can result in slower execution speeds for heavy computation.

Java combines the best of both worlds:
1. Compilation Phase (javac): Pre-compiles source code into Bytecode once, catching syntax errors and type mismatches ahead of time.
2. Interpretation & JIT Phase (JVM): The JVM interprets Bytecode immediately on startup for quick response times, while the JIT (Just-In-Time) compiler converts repetitive loops into pure native machine code, achieving near-C++ speeds!

3. Mandatory Java Source File Structure

A single .java source file follows a strict top-to-bottom structural hierarchy:

+-----------------------------------------------------------------------+
| 1. Package Declaration (Optional, must be first line if present)       |
|    package com.ourcompiler.tutorial;                                  |
+-----------------------------------------------------------------------+
| 2. Import Statements (Optional, imports external classes/libraries)   |
|    import java.util.Scanner;                                          |
|    import java.time.LocalDateTime;                                    |
+-----------------------------------------------------------------------+
| 3. Main Public Class Declaration (Must match filename exactly)        |
public class Application {
// 4. Class Variables & Fields (State)
private String appName = "OurCompiler Engine";
public static final int VERSION = 1;
// 5. Constructors (Object Initialization)
public Application() { ... }
// 6. Methods (Behavior)
public void start() { ... }
// 7. Main Entry Point Method
public static void main(String[] args) { ... }
}
+-----------------------------------------------------------------------+ | 8. Non-Public Classes (Optional, package-private helper classes) | | class HelperUtil { ... } | +-----------------------------------------------------------------------+

Fundamental Source File Rules:

1. Package Statement First: If a file belongs to a package (folder), the package statement must be the very first non-comment line. 2. Single Public Class Rule: A .java file can have at most one public class. 3. Filename Rule: The filename MUST match the name of the public class (e.g. Application.java for public class Application).

Beginner Example & Code Anatomy

โ˜• Main.java โ€” Chapter 3 Core Example
// 1. Package statement (conceptual for tutorial demonstration)
// package com.ourcompiler.demo;

// 2. Import statements from standard class library
import java.util.Date;
import java.time.LocalDate;

// 3. Primary public class matching filename: SourceStructureDemo.java
public class Main {
    
    // 4. Class-level constants & fields
    public static final String COURSE_NAME = "Java Masterclass 2026";

    // 5. Main execution entry point
    public static void main(String[] args) {
        System.out.println("Course Title   : " + COURSE_NAME);
        System.out.println("System Date    : " + new Date());
        System.out.println("Current Year   : " + LocalDate.now().getYear());
        
        // Calling a helper method
        displaySystemArchitecture();
    }

    // 6. Custom member method
    public static void displaySystemArchitecture() {
        System.out.println("Architecture   : 2-Step JIT Bytecode Compilation Model");
        System.out.println("Status         : Fully Compliant with Java 21 LTS Standard");
    }
}
๐Ÿ’ป Program Console Output
Course Title : Java Masterclass 2026 System Date : Sun Aug 16 13:45:00 IST 2026 Current Year : 2026 Architecture : 2-Step JIT Bytecode Compilation Model Status : Fully Compliant with Java 21 LTS Standard

๐Ÿ” Line-by-Line Code Explanation

import java.util.Date;

Imports the legacy Date class from the java.util standard library package.

public static final String COURSE_NAME

Declares a public, class-level, constant (final) String variable accessible everywhere.

displaySystemArchitecture();

Invokes the static member method defined within the same class.

public static void displaySystemArchitecture()

Method definition containing modular, reusable application logic.

Practical Real-World Example

โ˜• PracticalApplication.java โ€” Industry Implementation
// Multi-class demonstration in a single compilation unit
class DatabaseConnector {
    void connect() {
        System.out.println("[DatabaseConnector] Connected to PostgreSQL Database.");
    }
}

class SecurityGuard {
    boolean authenticate(String token) {
        return token.equals("AUTH_SECRET_2026");
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("--- Starting Enterprise Service Bootstrapping ---");
        
        SecurityGuard guard = new SecurityGuard();
        boolean isAuth = guard.authenticate("AUTH_SECRET_2026");
        System.out.println("Authentication Status: " + (isAuth ? "GRANTED" : "DENIED"));

        if (isAuth) {
            DatabaseConnector db = new DatabaseConnector();
            db.connect();
            System.out.println("System Ready for Production Traffic.");
        }
    }
}
๐Ÿ’ป Practical Console Output
--- Starting Enterprise Service Bootstrapping --- Authentication Status: GRANTED [DatabaseConnector] Connected to PostgreSQL Database. System Ready for Production Traffic.
โš ๏ธ Common Mistakes & Professional Best Practices
  • Placing import statements before package declaration: Causes a compile error. The package statement must always be first.
  • Declaring two public classes in one file: Causes compilation failure: "class X is public, should be declared in a file named X.java".
  • Running "java Main.class": The java command takes the CLASS NAME ("java Main"), not the filename with extension.
๐ŸŽฏ Hands-on Coding Challenge

Test your understanding by writing the code directly in your editor or running in our online Java compiler:

โ˜• Challenge.java
// Coding Challenge:
// Create a program containing:
// 1. A constant APP_NAME = "Enterprise Gateway"
// 2. A method named verifySystemStatus() that prints "[Status] All microservices operational."
// 3. Invoke verifySystemStatus() inside main().

public class Main {
    // TODO: Define APP_NAME constant here
    
    // TODO: Define verifySystemStatus() method here

    public static void main(String[] args) {
        // TODO: Print APP_NAME and call verifySystemStatus()
        
    }
}

๐Ÿ’ก Frequently Asked Questions & Interview Insights

โ“ What is inside a .class file?

A .class file contains binary Java Bytecode instructions, a constant pool (storing literal strings, numbers, and method references), class metadata, and stack/local variable allocations for the JVM.

โ“ Do I need to import java.lang classes like String or System?

No! The java.lang package is automatically imported by the Java compiler into every single Java file by default.

โ“ What is the command to view decompiled Bytecode?

You can use the built-in JDK disassembler: "javap -c Main.class" to inspect the human-readable JVM assembly instructions.

๐Ÿš€ Quick Chapter Recap

  • Java uses a 2-step compilation lifecycle: javac (Source to Bytecode) -> JVM (Bytecode to Machine Code).
  • Java source order: 1. package, 2. imports, 3. public class, 4. fields, 5. methods.
  • Only one public class is allowed per .java file and its name must match the filename.
โ† Prev: 2. Setup & First Program Next: 4. Comments & Naming Rules โ†’
OC
Curated by Our Compiler Java Technical Editorial Team
Published for 2026 Academic & Enterprise Reference ยท 100% Free & Open Access