Skip to content

Chapter 01Part I · Foundations

Why Java Exists

10 min read2 runnable examples

In this chapter: the problem Java was built to solve, what really happens between typing javac and seeing output, how the JDK, JRE and JVM fit together, and how "running a Java program" changed between Java 7 and Java 25.

Key points

  • javac compiles .java into platform-neutral bytecode (.class). A platform-specific JVM runs it: load → verify → interpret → JIT-compile the hot parts.
  • Objects live on the heap, method calls on per-thread stacks. Class metadata moved from PermGen to Metaspace in Java 8.
  • Java 11 dropped the separate JRE download; Java 9's jlink builds trimmed runtimes instead.
  • Every class file records its Java version: major − 44. Mismatch → UnsupportedClassVersionError. Compile with --release N.
  • Running Java got lighter: jshell (9), java Hello.java (11), multi-file launch (22), and in Java 25, a whole program can be void main() { IO.println("Hi"); }.

A program that only runs at home

Picture a team in the 1990s. They write a program in C++, compile it on a Windows machine and get a .exe file. The program works. A customer on a different operating system copies that file to their machine, double-clicks it, and nothing happens.

Nothing is wrong with the code. The problem is what the compiler produced. A C or C++ compiler turns source code directly into machine code: instructions for one kind of processor, wrapped in the file format and system calls of one operating system. That output is tied to the platform it was built for.

flowchart LR
    SRC["program.cpp"] --> CC["C++ compiler<br/>for Windows"]
    CC --> EXE["program.exe<br/>(Windows machine code)"]
    EXE -->|runs| W["Windows: runs"]
    EXE -.->|copied| L["Linux: won't run"]
    EXE -.->|copied| M["Mac: won't run"]

The traditional fix was to keep the source code and compile it again on every platform, with a compiler built for that platform. That works, but it has real costs:

  • Compilers are expensive to build. Each operating system and processor needs its own compiler, and the compilers don't always agree on the details.
  • You ship many binaries. One build per platform means one test cycle per platform.
  • Machine code is a dead end. You can't easily inspect it, check it for safety, or optimize it later for the machine it lands on.

The classic rule

"Problem → machine code is compatible to one particular environment. It will not run on another O.S. Solution → there should be a language where M.C can run on any O.S."

Still the best one-line summary of why Java exists.

Java's designers asked a different question: what if the compiler didn't produce machine code at all?

The middle language: bytecode

Java splits the work into two steps. The Java compiler, javac, turns your source code into bytecode: a compact set of instructions for a machine that doesn't physically exist. Then, on each computer, a program called the Java Virtual Machine (JVM) reads that bytecode and turns it into real machine code for that computer.

flowchart LR
    SRC["Hello.java"] --> JAVAC["javac<br/>(any platform)"]
    JAVAC --> BC["Hello.class<br/>bytecode"]
    BC --> JW["JVM for Windows"] --> W["runs on Windows"]
    BC --> JL["JVM for Linux"] --> L["runs on Linux"]
    BC --> JM["JVM for macOS"] --> M["runs on macOS"]

This is what "Write Once, Run Anywhere" means. The .class file is platform-independent, and the JVM is platform-dependent. Somebody still has to build a JVM for every platform, but that work is done once, by the people who make the JVM, and not by every application team.

Your first program, Java 7 style

Here is the classic first program. In Java 7 every one of these words was required, and each has a reason:

code/ch01/Hello.java
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello from the JVM!");
    }
}
Piece Why it's there
public class Hello All Java code lives inside a class. A public class must be saved in a file with the same name: Hello.java.
public The launcher, which lives outside your class, has to be allowed to call main.
static The launcher calls main before any object exists, so main must belong to the class rather than an instance.
void main returns nothing. A program reports success or failure with an exit code instead.
String[] args Command-line arguments. String... args (varargs, Java 5) also works.

Compile and run it in two steps:

$ javac Hello.java      # produces Hello.class
$ java Hello            # note: the class name, not the file name
Hello from the JVM!

What the JVM does when you press Enter

Inside the instance, your class goes through a pipeline:

flowchart TD
    A[".class file<br/>(disk, JAR or network)"] --> B["Class loader<br/>finds and reads the bytes"]
    B --> C["Bytecode verifier<br/>checks the bytes are safe to run"]
    C --> D["Interpreter<br/>runs bytecode right away"]
    D -->|"code runs often<br/>(a hot spot)"| E["JIT compiler<br/>compiles to native machine code"]
    E --> F["CPU runs native code"]
    D --> F

The class loader finds the bytes for a class, from a directory, a JAR file or anywhere else, and turns them into a class the JVM understands. Classes are loaded lazily, the first time they're needed, not all at startup.

The bytecode verifier checks that the bytes follow the rules: instructions are valid, types line up, the stack can't overflow or underflow, and code can't jump into the middle of an instruction. Class files can come from anywhere, so the JVM refuses to trust them blindly.

A common misconception

Java 7-era tutorials often said the verifier "removes viruses." It doesn't. It's not an antivirus and it doesn't remove anything. It rejects bytecode that breaks the JVM's safety rules, so a malformed or malicious class file can't corrupt memory. Code that is valid but harmful, such as a program that deletes your files, passes verification just fine.

The interpreter and the JIT compiler share the actual running. The interpreter starts executing bytecode immediately, which keeps startup fast. Meanwhile the JVM counts how often each method and loop runs. Code that runs a lot, a hot spot (hence the name HotSpot JVM), gets handed to the Just-In-Time (JIT) compiler, which compiles it into optimized machine code for the exact CPU it's running on. That's why a Java program often gets faster during its first few seconds: the JVM is still learning what to optimize.

Where things live: the JVM's memory areas

In the Java 7 era, the JVM's memory was usually drawn as a set of boxes. The picture still holds, with one important rename in Java 8.

flowchart TB
    subgraph SHARED["Shared by all threads"]
        direction LR
        MA["Method area<br/>class metadata, method bytecode,<br/>runtime constant pool<br/><i>(Metaspace since Java 8)</i>"]
        HEAP["Heap<br/>every object and array<br/><i>(managed by the garbage collector)</i>"]
    end
    subgraph PER["One per thread"]
        direction LR
        STACK["JVM stack<br/>one frame per method call:<br/>local variables, operands"]
        PC["PC register<br/>which instruction runs next"]
        NAT["Native method stack<br/>for code written in C/C++"]
    end
  • Method area. One copy of each loaded class: its methods' bytecode, field and method descriptions, and its runtime constant pool (the literals and symbolic references the class uses).
  • Heap. Every object you create with new lives here, no matter which method created it. The garbage collector reclaims objects nobody can reach anymore (Chapter 12).
  • Stack. Each thread has its own stack. Every method call pushes a frame holding that call's local variables and working values, and the frame disappears when the method returns. Too much recursion fills the stack and causes a StackOverflowError.
  • PC register. Each thread tracks which bytecode instruction it's executing.
  • Native method stack. Used when Java calls into code written in C or C++.

What changed: PermGen became Metaspace (Java 8)

In Java 7, HotSpot kept class metadata in a fixed-size heap region called the Permanent Generation (PermGen). Applications that loaded many classes, like app servers redeploying web apps, would crash with java.lang.OutOfMemoryError: PermGen space. Java 8 removed PermGen (JEP 122) and moved class metadata into Metaspace, which lives in native memory and grows as needed. The -XX:PermSize and -XX:MaxPermSize flags no longer apply. Use -XX:MaxMetaspaceSize if you want a cap.

JDK, JRE, JVM: then and now

These three acronyms confuse almost everyone at first. In the Java 7 world they nested neatly:

flowchart TB
    subgraph JDK["JDK — Java Development Kit (for developers)"]
        TOOLS["Development tools<br/>javac, javap, jar, javadoc, jdb …"]
        subgraph JRE["JRE — Java Runtime Environment (for users)"]
            LIBS["Class library<br/>java.lang, java.util … (rt.jar)"]
            JVM["JVM<br/>class loader, verifier, interpreter, JIT, GC"]
        end
    end
  • The JVM runs bytecode.
  • The JRE is the JVM plus the standard class library: everything needed to run a Java program. In Java 7 the library was packed into one large file, rt.jar.
  • The JDK is the JRE plus the tools to build programs: the compiler, disassembler, archiver, documentation generator and debugger.

In 2013, end users installed a JRE from java.com and developers installed the JDK. That split is mostly gone.

What changed: from one big JRE to custom runtimes

  • Java 9 (2017) split the platform into modules (JEP 200) and removed rt.jar and tools.jar (JEP 220). It also added jlink (JEP 282), which builds a runtime containing only the modules your application needs.
  • Java 11 (2018): Oracle stopped offering a separate JRE or Server JRE download. Only the JDK is offered, and you can use jlink to build a smaller runtime.
  • Today: applications usually ship with their own runtime, either inside a container image or bundled by jlink/jpackage, rather than relying on whatever JRE a user installed. Some vendors still publish JRE-style builds, but the "install Java on every PC" era is over.

You can see the modules in your own JDK with java --list-modules. On the JDK 21 used to test this book, the list has 69 entries, starting with java.base.

Every class file knows its Java version

Each .class file starts with the same four bytes, 0xCAFEBABE (a famous in-joke from the original Sun team), followed by a version number. The JVM reads that number before anything else and refuses class files that are newer than itself.

The rule is major version − 44 = Java version: Java 7 is 51, Java 25 is 69 and Java 27 is 71. This number explains one of the most common errors you'll ever see:

UnsupportedClassVersionError: Hello has been compiled by a more recent version
of the Java Runtime (class file version 65.0), this version of the Java Runtime
only recognizes class file versions up to 61.0

Translated: the class was built with Java 21, but you tried to run it on Java 17. Either upgrade the runtime, or compile with --release 17.

Migration tip: prefer --release over -source/-target

Java 7 projects used -source 1.7 -target 1.7. Those flags set the language level and class-file version, but they still compile against the current JDK's library, so you can accidentally call a method that doesn't exist on the older runtime. --release N (Java 9, JEP 247) checks against the real API of release N. In Maven that's <maven.compiler.release>; in Gradle, options.release.

How running Java changed: Java 7 → Java 25

For most of Java's history, "Hello, World" required a class, an access modifier, a static keyword, an array type and a System.out chain, all before a beginner wrote a single line of their own logic. Several releases chipped away at that ceremony.

timeline
    title Running a Java program
    2011 : Java 7 : javac Hello.java, then java Hello
    2017 : Java 9 : jshell, an interactive REPL
    2018 : Java 11 : java Hello.java runs a source file directly
    2023 : Java 21 : instance main methods (preview)
    2024 : Java 22 : source launcher runs multi-file programs
    2025 : Java 25 : compact source files and instance main methods (final)

Java 11: run a source file directly (JEP 330). java Hello.java compiles the file in memory and runs it, with no .class file left behind. Java 22 extended this to programs spread across several source files (JEP 458).

Java 25: compact source files and instance main methods (JEP 512). After four rounds of preview starting in Java 21, a complete program can now be this:

code/ch01/HelloCompact.java
void main() {
    IO.println("Hello from a compact source file!");
}
$ java HelloCompact.java
Hello from a compact source file!

Three things changed:

  1. No class declaration. A file with top-level methods and fields becomes a compact source file, and the compiler wraps it in an implicitly declared class.
  2. main can be an instance method, and needn't be public, static or take String[].
  3. IO.println. A new class, java.lang.IO, offers print, println and readln for console programs. Like everything in java.lang, it needs no import. Compact source files also import the whole java.base module automatically, so List, Map and friends work without import lines.

None of this replaces normal classes. Real applications still use packages, classes and the full public static void main. Compact source files are an on-ramp for learning, scripts and small tools.

Go deeper in the complete edition

This page is the focused edition. The complete edition of this chapter on GitHub adds the deep dives, puzzles, exercises and interview questions, with every sample ready to run.

Read the complete chapter →

Summary

  • C and C++ compile to machine code for one platform. Java compiles to bytecode, and a platform-specific JVM runs it anywhere.
  • Inside the JVM, classes are loaded, verified, interpreted, and the hot parts are JIT-compiled to native code.
  • Objects live on the heap. Each thread has its own stack of method frames. Class metadata lives in Metaspace since Java 8.
  • The JDK/JRE/JVM split changed: since Java 11, Oracle ships only the JDK, and jlink builds trimmed runtimes.
  • Running Java got simpler: jshell (9), single-file launch (11), multi-file launch (22), and compact source files with instance main (25).

Next: Chapter 2 looks at the values those programs work with: Java's eight primitive types, how they convert, and what var changed.