From Source File to Running Program
Brew Bar, a small café, wants a program that takes coffee orders. Before we write a single line of it, it helps to know what happens between typing Java and seeing it run. Most confusing beginner errors make sense once you know which stage raised them.
The rule
You write source, javac makes bytecode, and the JVM runs it.
A Java program passes through three stages.
- Source. You write human-readable code in a file ending in
.java, such asCafe.java. - Compile. The compiler,
javac, checks the whole file for grammar and type mistakes. If it finds none, it writesCafe.class. That file holds bytecode: compact instructions for an imaginary machine, not for your real processor. - Run. The command
java Cafestarts the Java Virtual Machine (JVM). The JVM loads the class, checks that the bytecode is safe, and executes it.
javac Cafe.java # creates Cafe.class
java Cafe # the JVM runs the bytecodeFor a quick experiment, modern Java also accepts java Cafe.java. It compiles in memory and runs straight away, without leaving a .class file behind. It is the same pipeline, only shorter to type.
Because bytecode targets the JVM rather than a particular chip, the same Cafe.class runs on Windows, macOS or Linux, as long as a JVM is installed. The JVM starts by interpreting bytecode. When it notices a method running again and again, its JIT (just-in-time) compiler translates that method into native machine code, which is why long-running Java programs get faster after a warm-up.
You install all of this as the JDK (Java Development Kit), which contains javac, the JVM and the standard library.
The shortcut
When something goes wrong, ask "Did javac complain, or did the JVM?"
- javac errors appear before anything runs: a missing semicolon, a misspelled name, putting text into a number variable.
- JVM errors appear while the program runs, as an exception: dividing a whole number by zero, reading past the end of an array.
Write
You save
Cafe.javacontaining a class namedCafewith amainmethod.
The trap is thinking "it compiled, so it works". The compiler checks the shape of the program, not the values it will meet at run time.
Drills
Answer fast — trust the rule.
What does javac Cafe.java produce when there are no errors?
The line int cups = "two"; is in your file. When is the mistake reported?
int perCup = total / cups; compiles, but cups holds 0 when the line runs. What happens?
Which part turns frequently used bytecode into native machine code?
You copy Cafe.class from a Mac to a Linux laptop with Java installed. What do you need to do?
Remember
- Source (
.java) → javac → bytecode (.class) → JVM runs it. - Ask "javac or JVM?": compile errors come before running, exceptions come during.
- Compiling proves the shape is right, not that the values will be.
