Course outline · 0% complete

0/29 lessons0%

Course overview →

Compile first, run second

lesson 1-2 · ~7 min · 2/29

The compile mental model

Python reads your file top to bottom and executes it directly. Java adds a step in the middle, and the step is the point: it finds mistakes before the program runs, not while a customer is using it. Here is the pipeline:

  1. You write Main.java, plain source text.
  2. The compiler (javac) reads the whole file, checks every type and every semicolon, and produces Main.class. That file contains bytecode: compact instructions written for the Java Virtual Machine rather than for any one physical CPU. Because the instructions are machine-neutral, the same compiled file can travel to any computer.
  3. The Java Virtual Machine (JVM) runs the bytecode on your real machine.

The payoff: the same Main.class runs on Windows, Mac, and Linux, because each machine has its own JVM that speaks its native CPU language. And because the compiler checks everything before anything runs, whole categories of typos never make it to a running program.

Main.javasource you writeMain.classbytecodeJVMruns it anywherejavac compilesjava runs
One program, three stages: your source is compiled to bytecode once, then the JVM runs that bytecode on any machine.

Types are declared

The compiler can only check your program because you tell it the type of every variable when you create it:

int year = 1995;
String name = "Java";

int means whole number, String means text. Compare Python's year = 1995, where the type is discovered while running. In Java, writing year = "hello" later is a compile error. The program never runs with that mistake in it. You will meet all the core types in the next unit.

Compile-time vs runtime errors

The compile step splits all mistakes into two families, and knowing which family you are fighting saves debugging time every single day:

  • A compile-time error breaks a rule the compiler can verify by reading the code: a missing semicolon, a misspelled name, assigning text to an int. The program never starts. javac prints the file, line number, and problem.
  • A runtime error only appears while the program runs, because it depends on actual values: dividing by a variable that happens to be zero, or asking for position 10 of a 3-element array. The compiler cannot see the future, so these still crash.

Java's design pushes as many mistakes as possible into the first family — a compile error costs you seconds, a runtime error in production can cost a company an outage.

Quiz

Which of these mistakes does the Java compiler catch before the program ever runs?

Code exercise · java

Run this program with a declared int variable. Then try changing 1995 to the text "nineteen95" and run again to watch the compiler reject it before anything executes. Change it back to finish.

Quiz

You write a Java program with a typo: Systm.out.println. When do you find out?