Part 1 · The core language

1How Java runs

Before you write a real program you need an accurate picture of what happens between typing text into a file and seeing something appear on screen. This lesson builds that picture, then uses it to explain every word of the smallest Java program and the errors you will meet most often.

By the end you will be able to

  • explain what javac and java each do, and what a .class file is
  • write, compile and run a program from the terminal
  • say what each word of public static void main(String[] args) is for
  • print text that contains quotes, tabs, new lines and backslashes
  • read a compiler error, and tell compile-time, launch and run-time failures apart

A program is a text file

A computer's processor understands only machine instructions: numbers that mean things like add these two values, copy this value over there or jump to that instruction. Nobody writes those numbers by hand. A programming language lets you describe what you want in a readable form, and a tool translates your description into something the machine can carry out.

What you write is called source code. Java source code is plain text saved in a file whose name ends in .java. Plain text means the file contains only the characters you typed: no fonts, no bold, nothing hidden. That is why you write code in a code editor such as VS Code and never in a word processor.

The readable form has strict rules, called the language's syntax. A human reader fills in a missing full stop without noticing. The translator does not guess: one missing semicolon and it stops and tells you. That strictness is what lets a program mean exactly one thing.

Two steps: compile, then run

Getting from a Java source file to a running program takes two steps, compiling and running. Normally each is done by its own tool.

STEP 1 · COMPILE STEP 2 · RUN HelloWorld.java source code text you write javac the compiler HelloWorld.class bytecode instructions for the JVM java starts a JVM Hello, world! your program running checks your code, then translates it carries out the instructions

Step 1, compile. The tool javac (the Java compiler) reads your .java file and checks it against the rules of the language. If it finds a problem it reports it and produces nothing. If the file passes, javac writes a new file ending in .class that contains bytecode.

Bytecode is a compact set of instructions. It is not written for the processor in your computer. It is written for an imaginary computer called the Java Virtual Machine, or JVM.

Step 2, run. The tool java starts a JVM: a real program on your computer that plays the part of that imaginary machine. It loads your .class file and carries out the bytecode instructions one after another, translating them into real instructions for your actual processor as it goes.

Why two steps?

Three names you will keep seeing

NameWhat it is
JVMThe program that runs bytecode. You start one each time you type java.
JDKThe Java Development Kit: what is installed on your computer. It contains a JVM, the standard library (thousands of ready-made classes, including the one that prints text), and the developer tools: javac, plus others: javadoc, which lesson 29 covers, and javap, which the section Looking inside a class file uses.
JREThe Java Runtime Environment: a JVM and the standard library without the developer tools. It is enough to run programs but not to compile them. You will see the term in older articles; to write Java you want a JDK.

Check your tools

In VS Code, choose File › Open Folder and open your course folder, the one you unzipped the course kit into (for example java-course). Then open a terminal with Ctrl+` (the key above Tab), or Terminal › New Terminal.

A terminal is a window where you type a command, press Enter, and read the reply. On Windows it runs a program called PowerShell. The text to the left of your cursor is the prompt; it shows which folder you are currently in, and commands act on that folder. Three commands are enough to get around:

CommandWhat it does
cd nameMoves into the folder called name. Press Tab after the first few letters and the terminal completes the name for you.
cd ..Moves up to the folder that contains the current one.
lsLists what is in the current folder. ls -Name lists the names only.

Now ask both tools for their version numbers. On this page, lines starting with > are what you type (without the >); the other lines are the computer's reply.

Terminal
> java -version
java version "27.0.1.0.3" 2026-10-25
Java(TM) SE Runtime Environment (build 27.0.1.0.3+1-2)
Java HotSpot(TM) 64-Bit Server VM (build 27.0.1.0.3+1-2, mixed mode, sharing)
> javac -version
javac 27.0.1.0.3

That output was captured on the computer this course was tested on, and this course was built and tested with that version. If either command answers that it is not recognized or command not found, the JDK is missing or the terminal cannot find it. Go back to the installation steps in Start here, which explain how the terminal finds the JDK, and check them again before going on.

Your first program

Do these steps yourself as you read.

  1. In VS Code's file explorer, find work/m01-how-java-runs in your course kit and create a new folder inside it called hello.
  2. Inside hello, create a new file called HelloWorld.java. The capital H and capital W matter, and there are no spaces.
  3. Type the following into the file, exactly. Type it; do not paste it. Then save with Ctrl+S.
code/m01-how-java-runs/hello/HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

In the terminal, move into the folder with cd work\m01-how-java-runs\hello. Then compile, look at what appeared, and run:

Terminal, in your hello folder
> javac HelloWorld.java
> ls -Name
HelloWorld.class
HelloWorld.java
> java HelloWorld
Hello, world!

Three things to notice.

Predict

You change the text in HelloWorld.java to "Hello again!" and save the file. Then, without compiling, you type java HelloWorld. What is printed?

Reveal the answer

The old text: Hello, world! The java tool runs the .class file, and the .class file is only as new as the last time you ran javac. Your edit exists in the source file but not yet in the bytecode.

The cycle is always edit, save, compile, run. Skipping save or compile is the most common reason for my change did nothing. Try it now and see it happen.

Every word of HelloWorld

The program is five lines long, and nothing in it is decoration. Some words can only be fully explained later in the course; for those you get an accurate short version now and the lesson where the full story comes.

Line 1: the class

public class HelloWorld {

class HelloWorld declares a class and gives it the name HelloWorld. In Java, all code lives inside a class. For now, think of a class as a named container for code. From lesson 8 onwards a class becomes much more than that, but the container picture is correct as far as it goes. Class names are written with a capital letter at the start of each word and no spaces.

public means the class may be used from anywhere. It has one consequence that matters today: a public class must be saved in a file with exactly the same name, plus .java. The class HelloWorld lives in HelloWorld.java, capital letters included.

{ opens the body of the class, and the } on line 5 closes it. Braces always come in pairs, and everything between a pair is inside.

Line 2: the main method

    public static void main(String[] args) {

This line declares a method: a named block of instructions. When you type java HelloWorld, the JVM loads the class and looks inside it for a method called main. That method is where the program starts, so it is called the entry point. The line above is its standard form, and each word in it has a job:

WordIts jobFull story
publicMakes the method usable from outside the class. The JVM, which calls it, is outside.Lesson 9
staticThe method belongs to the class itself, not to an object made from the class. That lets the JVM call it straight away, without creating anything first.Lessons 8 and 11
voidThe method hands no result back to whoever called it.Lesson 5
mainThe method's name. The JVM looks for this name specifically; Main or start will not do.
(String[] args)The method's parameter: a list of pieces of text. It receives any extra words typed after the class name, so java HelloWorld red blue would deliver red and blue. This program ignores it.Lessons 5 and 7

It is fine to treat this line as a fixed formula for a few lessons. The point of the table is that the formula is not magic. Each word is an ordinary part of the language, and each will be explained properly.

Line 3: the statement

        System.out.println("Hello, world!");

This is the only line that does something you can see. It is a statement: one complete instruction. Take it apart from the inside out:

Lines 4 and 5 are the closing braces of the method and of the class.

Three rules that apply everywhere

  1. Java is case-sensitive. System and system are different names. So are main and Main.
  2. Layout is for humans. Outside string literals, the compiler does not care about extra spaces, blank lines or indentation; this whole program could legally sit on one line. People care a great deal. The convention is to indent four spaces for each brace you are inside, which makes the structure visible and a missing brace easy to spot.
  3. Braces, parentheses and quotes come in pairs. Most beginners' errors are an unpaired one of these or a missing semicolon.

Statements run in order

A method can hold any number of statements. The JVM carries them out one at a time, starting at the top of main and working down. When it reaches the closing brace of main, the program ends.

code/m01-how-java-runs/TeaTime.java
// Prints the steps for making a cup of tea.
// Statements run one at a time, from the top of main to the bottom.
public class TeaTime {
    public static void main(String[] args) {
        System.out.println("1. Boil the water.");
        System.out.println("2. Add the tea bag.");

        // print does NOT end the line, so the next output continues on it.
        System.out.print("3. Wait");
        System.out.print("...");
        System.out.println(" three minutes.");

        System.out.println();   // prints an empty line
        System.out.println("Enjoy!");
    }
}
Terminal, in code/m01-how-java-runs
> javac TeaTime.java
> java TeaTime
1. Boil the water.
2. Add the tea bag.
3. Wait... three minutes.

Enjoy!

Compare the code with its output and three new things appear.

print and println are different. println prints its text and then ends the line, so the next output starts on a fresh line. print prints its text and stays where it is. Lines 9 to 11 are three separate statements that together produce one line of output.

println() with nothing in the parentheses prints no text and ends the line. The result is an empty line.

Comments. Everything from // to the end of that line is a comment. The compiler ignores it completely; it is a note for whoever reads the code, including you next month. A longer comment can start with /* and run across several lines until */. A good comment says why something is done, since the code already shows what.

Predict

Write down exactly what these five statements print, line by line.

code/m01-how-java-runs/predict/Mixed.java (lines 3 to 7)
System.out.print("A");
System.out.println("B");
System.out.print("C");
System.out.println();
System.out.println("D");
Reveal the answer
Terminal, in code/m01-how-java-runs/predict
> javac Mixed.java
> java Mixed
AB
C
D

A is printed and the line stays open, so B lands next to it and then the line ends. C is printed and the line stays open; the empty println() ends it. D gets a line of its own. There is no blank line anywhere, because every end the line came after some text on that line.

Special characters inside text

A string literal starts and ends with a double quote. So how do you print a double quote? If you simply type one, the compiler takes it as the end of the text. And how do you put a line break inside a text, when a string literal is not allowed to run past the end of a line of source code?

The answer is an escape sequence: a backslash followed by one character. The pair is written as two characters in your source but stands for a single special character in the text.

You writeIt stands for
\na new line
\ta tab: a jump to the next tab stop
\"a double quote that does not end the text
\\one backslash
code/m01-how-java-runs/Postcard.java
public class Postcard {
    public static void main(String[] args) {
        // \n starts a new line inside a single piece of text.
        System.out.println("Dear Sam,\nThe weather is lovely.");

        // \t jumps to the next tab stop, which lines text up in columns.
        System.out.println("Mon\tsunny");
        System.out.println("Friday\train");

        // \" puts a double quote inside the text without ending it.
        System.out.println("The guide said \"mind the step\" twice.");

        // \\ prints one backslash.
        System.out.println("Photos are in D:\\holiday\\day1");
    }
}
Terminal, in code/m01-how-java-runs
> javac Postcard.java
> java Postcard
Dear Sam,
The weather is lovely.
Mon	sunny
Friday	rain
The guide said "mind the step" twice.
Photos are in D:\holiday\day1

Read "Friday\train" carefully. The escape sequence is \t and the word after it is rain. An escape sequence is always exactly two characters, the backslash and the one character after it, even when more letters follow.

The last row of the table follows from the others. Because a backslash announces an escape sequence, a backslash that you actually want printed has to be escaped itself. That matters on Windows, where folder paths are full of them.

A tab does not mean eight spaces. It means move to the next tab stop, and terminals normally place a tab stop every eight columns. That is why sunny and rain start in the same column even though Mon and Friday are different lengths.

Predict

These two statements differ by one backslash. What does each print?

code/m01-how-java-runs/predict/Slashes.java (lines 3 to 4)
System.out.println("one\ntwo");
System.out.println("one\\ntwo");
Reveal the answer
Terminal, in code/m01-how-java-runs/predict
> javac Slashes.java
> java Slashes
one
two
one\ntwo

The first statement prints two lines, because \n is an escape sequence and breaks the text. The second prints the single line one\ntwo. There the compiler reads \\ first: an escaped backslash, which stands for one ordinary backslash. The n after it is then just the letter n.

When it goes wrong: three kinds of failure

Errors are a normal part of programming, and experienced programmers see dozens a day. The two-step picture tells you when a problem can show itself, and knowing when is half of knowing what to do about it.

KindWho reports itWhenWhat it means
Compile-time errorjavacStep 1The source breaks a rule of the language. No .class file is written.
Launch errorjavaStep 2, before your code startsThe JVM could not find the class you named, or could not find a usable main in it.
Run-time errorThe JVMStep 2, while your code runsA statement asked for something impossible. Everything before it has already happened.

Reading a compiler error

This file is missing one character.

code/m01-how-java-runs/broken/MissingSemicolon.java
public class MissingSemicolon {
    public static void main(String[] args) {
        System.out.println("Almost right")
    }
}
Terminal, in code/m01-how-java-runs/broken
> javac MissingSemicolon.java
MissingSemicolon.java:3: error: ';' expected
        System.out.println("Almost right")
                                          ^
1 error

An error in your code is reported in these four parts. Some errors add a line or two of extra detail, as you will see below.

  1. MissingSemicolon.java:3: gives the file and the line number.
  2. error: ';' expected is the message. It nearly always describes what the compiler expected to find or could not find.
  3. The source line, with a caret (^) under the exact spot.
  4. 1 error, the total.

Look closely at where the caret is: at the very end of the line, after the closing parenthesis. The compiler reports the place where it noticed that something was wrong. Often, as here, that is exactly where the fix belongs. Sometimes it is a long way from it:

code/m01-how-java-runs/broken/Unclosed.java
public class Unclosed {
    public static void main(String[] args) {
        System.out.println("Where does the class end?");
    }
Terminal, in code/m01-how-java-runs/broken
> javac Unclosed.java
Unclosed.java:4: error: reached end of file while parsing
    }
     ^
1 error

Reached end of file while parsing means the compiler arrived at the end of the file still waiting for a closing brace. The class was opened on line 1 and never closed. The compiler cannot know where you meant the brace to go, so it can only point at where the file ran out. This is the practical reason to indent consistently: with every block indented, the brace that is missing shows in the shape of the code.

Messages that need translating

Some messages are accurate but do not say what you would expect. These two are the ones beginners meet most.

code/m01-how-java-runs/broken/Typo.java
public class Typo {
    public static void main(String[] args) {
        System.out.printn("One letter short");
    }
}
Terminal, in code/m01-how-java-runs/broken
> javac Typo.java
Typo.java:3: error: cannot find symbol
        System.out.printn("One letter short");
                  ^
  symbol:   method printn(String)
  location: variable out of type PrintStream
1 error

Cannot find symbol is one of the most common compiler errors. A symbol is simply a name. The message means: you used a name, and I can find nothing with that name here. The two extra lines say which name (method printn(String)) and where the compiler looked for it. With what you know so far, the cause will be a spelling mistake or wrong capitalisation.

code/m01-how-java-runs/broken/WrongCase.java
public class WrongCase {
    public static void main(String[] args) {
        system.out.println("Capital letters matter");
    }
}
Terminal, in code/m01-how-java-runs/broken
> javac WrongCase.java
WrongCase.java:3: error: package system does not exist
        system.out.println("Capital letters matter");
              ^
1 error

There is no package involved here; the mistake is a lower-case s. The compiler could find nothing called system, and for a lower-case name followed by a dot its best guess was a package, which is a named group of classes (lesson 12). The guess about what is wrong is poor. The line number and the caret are exactly right. When a message makes no sense, trust the location and look at the code there.

One message looks different from all of these, because it is not about your code at all:

Terminal, in your hello folder
> javac HelloWord.java
error: file not found: HelloWord.java
Usage: javac <options> <source files>
use --help for a list of possible options

File not found means javac could not find a file with the name you typed. Either the name is misspelt or you are in the wrong folder. Use ls to see what is actually there.

A method for any compiler error

  1. Read only the first error. Later ones are often side effects of the first.
  2. Go to the line number. Look at that line and at the line before it.
  3. Read the message literally. What did the compiler expect, or fail to find?
  4. Fix one thing, save, and compile again.

Launch errors

This file compiles, because nothing in the language forbids a method called Main.

code/m01-how-java-runs/WrongMain.java
public class WrongMain {
    // Capital M: to Java this is a different name from "main".
    public static void Main(String[] args) {
        System.out.println("Will this run?");
    }
}
Terminal, in code/m01-how-java-runs
> javac WrongMain.java
> java WrongMain
Error: Main method not found in class WrongMain, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

The compiler was satisfied and wrote a .class file. The failure came from java, which looked in the class for an entry point and found none. The message even shows you the line it wanted. (Its last line mentions JavaFX, the graphics library you will use in Part 7. Ignore it until then.)

Two more launch errors come from what you type after java:

Terminal, in your hello folder
> javac HelloWorld.java
> java HelloWorld.class
Error: Could not find or load main class HelloWorld.class
Caused by: java.lang.ClassNotFoundException: HelloWorld.class
> java helloworld
Error: Could not find or load main class helloworld
Caused by: java.lang.NoClassDefFoundError: helloworld (wrong name: HelloWorld)

In the first, java was given a file name where it wanted a class name, so it went looking for a class literally called HelloWorld.class. In the second, the capitalisation is wrong. Windows does not distinguish upper and lower case in file names, so the file was found; the JVM then opened it, saw that the class inside is called HelloWorld, and refused: wrong name.

Run-time errors

code/m01-how-java-runs/Crash.java
public class Crash {
    public static void main(String[] args) {
        System.out.println("Sharing 10 sweets...");
        System.out.println(10 / 0);
        System.out.println("Done.");
    }
}
Terminal, in code/m01-how-java-runs
> javac Crash.java
> java Crash
Sharing 10 sweets...
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Crash.main(Crash.java:4)

Follow what happened.

A failure of this kind is called an exception, and the report is a stack trace. Lesson 17 is about exceptions. Until then, read the first line for what and the at line for where.

Predict

A file called Party.java contains the following. Which of the three kinds of failure occurs, and what will the message say is wrong?

code/m01-how-java-runs/broken/Party.java
public class party {
    public static void main(String[] args) {
        System.out.println("Everyone is invited");
    }
}
Reveal the answer
Terminal, in code/m01-how-java-runs/broken
> javac Party.java
Party.java:1: error: class party is public, should be declared in a file named party.java
public class party {
       ^
1 error

A compile-time error. The class is public, so its name must match the file name exactly, and party is not Party. You can fix it either by renaming the class to Party or by renaming the file. Renaming the class is right here, because class names start with a capital letter.

Two shortcuts you will see elsewhere

Recent versions of Java offer shorter ways to write and run small programs. You should recognise both, and know why this course does not rely on them.

Running a source file directly

Terminal, in your hello folder
> java HelloWorld.java
Hello, world!
> ls -Name
HelloWorld.java

This is the one case where java accepts a file name. Given a name ending in .java, it compiles that file in memory and runs it straight away. Both steps still happen, inside one tool, and no .class file is written to disk: the listing shows only the source file. It is handy for a quick experiment. This course uses the two separate commands, because real programs are made of many files and are always compiled first, and because seeing both steps keeps the picture clear.

Compact source files

Since Java 25, a small program can leave out most of the ceremony:

code/m01-how-java-runs/modern/Modern.java
void main() {
    IO.println("Hello from a compact source file!");
}
Terminal, in code/m01-how-java-runs/modern
> java Modern.java
Hello from a compact source file!

There is no class declaration, no public static, no String[] args, and IO.println replaces System.out.println. The compiler wraps the code in a class for you, and this shorter main is one of the forms the JVM has accepted since Java 25. This form exists to make first programs and small scripts less intimidating.

This course uses the full form throughout. Nearly all existing Java code uses it, and programs made of several classes are written in it. You also now know what each word of the full form is for, which is the reason the short form could be invented.

Looking inside a class file

This section is optional. The JDK includes a tool called javap that shows the contents of a .class file in readable form.

Terminal, in your hello folder
> javac HelloWorld.java
> javap -c HelloWorld
Compiled from "HelloWorld.java"
public class HelloWorld {
  public HelloWorld();
    Code:
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return

  public static void main(java.lang.String[]);
    Code:
         0: getstatic     #7                  // Field java/lang/System.out:Ljava/io/PrintStream;
         3: ldc           #13                 // String Hello, world!
         5: invokevirtual #15                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
         8: return
}

Look at the four lines under main. That is your one statement, as the JVM sees it: getstatic fetches System.out, ldc loads the text Hello, world!, invokevirtual calls println, and return ends the method. The first block, public HelloWorld(), is something the compiler added that you did not write; lesson 8 explains what it is.

You will never need to read bytecode in order to write Java. The point is only that a .class file is not mysterious. It is your program, translated into smaller steps.

Exercises

Each exercise has a folder waiting in work/m01-how-java-runs/ in your course kit. Compile and run from the terminal, inside the exercise's folder. Open a hint only after a real attempt.

warm-up

Exercise 1.1 · Business card

Work in work/m01-how-java-runs/ex1-business-card/ in your course kit

Starting from an empty file, write a program Card.java that prints a business card for yourself or for an invented person. Type the whole file yourself, including the first two lines.

  • The class is called Card.
  • The card has a border drawn with +, - and |, and every line of the card is the same width.
  • Inside are at least four lines: a name, a role, an empty line, and a motto.
  • The motto is printed with double quotes around it.

Here is the output of one possible card. Yours should have your own content.

Example output of java Card
+----------------------------+
| Robin Okafor               |
| Apprentice Java programmer |
|                            |
| "Compile early, run often" |
+----------------------------+
Hint 1

Each line of the card is one println. Write the top border first and run the program before going further.

Hint 2

A \" takes two characters in your source but prints as one. A line containing two of them looks two characters too long in the editor, and that is correct. Judge the widths from the output, not from the source.

To check it, run python check.py m01 ex1 in your course kit folder.

warm-up

Exercise 1.2 · Exact output

Work in work/m01-how-java-runs/ex2-escape-sequences/ in your course kit

Write Escapes.java (class Escapes) so that its output is exactly these five lines, character for character. The gap in the third line and the gap in the fourth line are each a single tab character.

Required output of java Escapes
She said, "Java is not JavaScript."
Folder: C:\courses\java\module01
Name	Role
Ada	Author
Tabs are written \t and new lines \n.

One constraint: the third and fourth lines (the ones starting Name and Ada) must both come from a single println statement.

Hint 1

Go through the required output and mark every character that cannot be typed plainly inside a string literal. There are four different kinds.

Hint 2

The last line has to show a backslash followed by the letter t. Look again at the predict box at the end of the section Special characters inside text.

To check it, run python check.py m01 ex2 in your course kit folder.

core

Exercise 1.3 · Bug hunt

Work in work/m01-how-java-runs/ex3-bug-hunt/ in your course kit

Your folder contains Itinerary.java, which has six mistakes in it, and a file bug-log.md. Get the program to compile and print the four-line itinerary below, following these rules:

  • Compile first. Read the first error, fix that one mistake, and compile again. Repeat.
  • For every mistake, add an entry to bug-log.md: the compiler's message, the line it pointed at, what was actually wrong, and what you changed.
  • Do not rename the file.
work/m01-how-java-runs/ex3-bug-hunt/Itinerary.java
public class itinerary {
    public static void main(String[] args) {
        System.out.println("Day 1: Lisbon")
        system.out.println("Day 2: Porto");
        System.out.println("Day 3: Coimbra);
        System.out.printn("Day 4: Faro");
    }
Output of java Itinerary when all six are fixed
Day 1: Lisbon
Day 2: Porto
Day 3: Coimbra
Day 4: Faro

At the end of bug-log.md, answer one question in your own words: the compiler did not report all six mistakes the first time. Why not?

Hint 1

If a message seems to make no sense, trust the line number and the caret, and compare that line character by character with a line that works.

Hint 2

For the final question, reread the Going deeper box in the section When it goes wrong.

To check it, run python check.py m01 ex3 in your course kit folder.

core

Exercise 1.4 · Break it on purpose

Work in work/m01-how-java-runs/ex4-break-it-on-purpose/ in your course kit

Your folder contains a working program, Signal.java, and a notes file to fill in, lab-notes.md. Compile and run the program once to confirm it works. Then carry out the seven experiments below. Before each one, write your prediction in the notes file. After each one, undo the change so the next experiment starts from the working program.

  1. Delete Signal.class (right-click it in VS Code's file explorer and choose Delete), then run java Signal. Compile again afterwards to get the file back.
  2. Change String[] args to String args.
  3. Remove the word static.
  4. Change println to Println on one line.
  5. Move one of the println statements up, so that it sits directly inside the class but outside main.
  6. Leave the file alone, compile it, and run java signal.
  7. Remove the word public in front of class.

For each experiment record: what you predicted; what happened (compile-time error, launch error, run-time error, or it works); the key line of any message; and one sentence, in your own words, explaining why. Two of the seven hold a surprise. Finish with Signal.java back in its original working state.

Hint

For every experiment ask the same two questions. Does javac still accept the file? If it does, can java still find a class with the right name and an entry point in it?

To check it, run python check.py m01 ex4 in your course kit folder.

stretch

Exercise 1.5 · Two classes, one file

Work in work/m01-how-java-runs/ex5-two-classes-one-file/ in your course kit

So far every file has held exactly one class. Find out what happens with two. Write a single file Orchestra.java containing:

  • a public class Orchestra whose main prints The orchestra tunes up.
  • below it, a second class Violin, declared without the word public, whose own main prints A violin plays alone.

Compile the file, list the folder, and try to run each class. Then answer the three questions in answers.md:

  1. How many .class files did one .java file produce, and what does that tell you about what a .class file holds?
  2. Add public in front of class Violin and compile. Quote the error and explain the rule behind it. (Then take public out again.)
  3. To run a compiled program, java takes the name of a class and not the name of a file. What did you see in this exercise that proves it?
Hint

The second class goes after the closing brace of the first, not inside it. Each class has its own pair of braces and its own complete main.

To check it, run python check.py m01 ex5 in your course kit folder.

Summary

Words introduced in this lesson

TermMeaning
Source codeThe text of a program, as written by a person.
CompilerA tool that checks source code and translates it into another form. Java's is javac.
BytecodeThe instructions in a .class file, written for the JVM.
JVMJava Virtual Machine: the program that runs bytecode.
JDKJava Development Kit: the JVM, the standard library and the developer tools.
ClassFor now, a named container for code. All Java code is inside one.
MethodA named block of statements. main is the one where a program starts.
StatementOne complete instruction, ending in a semicolon.
String literalText written directly in the source between double quotes.
ArgumentA value handed to a method between its parentheses.
Escape sequenceA backslash and a character that together stand for one special character.
CommentA note in the source that the compiler ignores.
ExceptionA failure while the program is running.
Stack traceThe report printed for an exception, saying what failed and where.