What a Program Is, and Your First One

What a computer is underneath the screen, what a program is made of, and the anatomy of Hello World — class, method, statement — followed by the two commands that turn source code into output. Follows Think Java 2e, Chapter 1 (Computer Programming), Sections 1.1-1.4, pp. 1-6, cross-referenced against The Java Tutorials — Getting Started: The 'Hello World!' Application.

Subject: Java · 65 slides · code lesson

Open the interactive version of this deck

What this lesson covers

The lesson, slide by slide

1. What a Program Is, and Your First One

Title

Think Java 2e · Chapter 1 · Computer Programming

Sections 1.1-1.4 · pp. 1-6

2. What you will be able to do

Objectives

This lesson follows Think Java 2e, Chapter 1 (Computer Programming), Sections 1.1-1.4, pp. 1-6. Everything on these slides can be checked against those pages.

1. Say what the two hardware components that actually compute are, and why everything else is a peripheral.

2. List the five kinds of instruction that appear in essentially every programming language.

3. Name every part of the Hello World program: the class, the method, the statement, the comment, and the braces that group them.

4. Explain why the file must be called Hello.java when the class is called Hello.

5. Run javac and java in the right order, and say what file each one produces or consumes.

6. Explain what the Java Virtual Machine buys you, in terms of a program you compile once and run in two places.

3. Before we start: what is a computer?

Warm-up

You have used computers for years. That is exactly why this question is worth two minutes — familiarity hides the answer.

Discussion prompt

Without looking anything up: name every device you own that you would call a computer. Then name three devices you would NOT call a computer, and say what is missing from them.

Hint: Think about what a device has to be able to do before the word applies.

Answer:

Think Java's answer is deliberately broad: a computer can be any type of device that stores and processes data. By that definition your microwave and your car's engine controller are computers, and your third list is probably shorter than you expected.

That breadth matters. The rest of this course is about instructing a machine that stores and processes data — and it does not care whether that machine is a laptop, a phone, or a thermostat.

4. Where this lesson is going

Concept

By the end of this lesson you will have a complete Java program, you will know the name and job of every single character in it, and you will know what happens between pressing run and seeing output.

Figure (svg): Five boxes left to right: Hello.java, javac, Hello.class, java, then the words Hello, World! as output

Downey & Mayfield, Think Java, 2nd edition (Green Tea Press / O'Reilly, 2020) — Think Java 2e, Chapter 1 (Computer Programming), Sections 1.1-1.4, pp. 1-6 — Chapter 1 opens on printed page 1.

5. What a computer actually is

Section

Section 1.1

6. Two components do the computing

Concept

Every computer, from a smartphone to a mainframe, shares the same two important hardware components. Everything else — the screen, the keyboard, the touch sensor — is how a human gets data in and out. The computing itself happens in only two places.

Figure (svg): Two boxes: processor, which performs simple calculations, and memory, which temporarily stores information

processor (CPU) — The hardware component that performs simple calculations, one after another, very fast.

memory (RAM) — The hardware component that temporarily stores information while the program runs.

Think Java notes the scale: it is fairly standard even for a smartphone to have at least eight processors and four gigabytes — four billion cells — of memory.

7. A modern phone, drawn honestly

Picture it

If you drew a phone the way a computer scientist sees it, the glass would be the smallest part of the picture.

Figure (svg): Three boxes: eight or more processors, four gigabytes of memory, and screen and sensors marked as input and output

Keep this picture. In two chapters, when we draw a memory diagram, we will be drawing the middle box.

8. Counting the computers in one room

Worked example

Apply the definition — stores and processes data — to an ordinary kitchen, and count. This is not a trick; it is the definition doing its job.

Start with the obvious ones: a laptop on the table, a phone on the counter.

Why: Both plainly store and process data.

Add the microwave.

Why: It stores a cooking time you typed in and processes a countdown. It qualifies.

Add the dishwasher with a cycle selector, and the thermostat on the wall.

Why: Both store a setting and process it into behaviour over time.

Now try to exclude the kettle with a single on/off switch.

Why: It processes nothing and stores nothing — the switch completes a circuit. It does not qualify.

Verify: Count again and say the number out loud: four computers, one appliance.

Why: If your count changed when you applied the definition instead of your intuition, the definition is doing exactly what a definition is for.

9. Is a smart doorbell a computer?

Prediction

Apply the definition rather than your intuition.

Predict first

By Think Java's definition — a device that stores and processes data — is a video doorbell a computer?

  • Yes
  • No
  • Only while someone is pressing it
  • Only if it is connected to the internet

Correct: Yes

Why: It stores data (video footage, a motion threshold, your settings) and processes it (detecting motion, encoding video, deciding when to notify you). Both halves of the definition are satisfied, so it is a computer — internet connection or not. The connection changes where the data goes, not whether it is processed.

10. Why the definition is drawn this wide

Concept

It would be easier to define a computer as a laptop or a phone. Think Java refuses to, and the reason is practical rather than pedantic: the skills in this book apply to anything that stores and processes data. Narrowing the definition would narrow what you think the skills are for.

devicestores data?processes it?a computer?
laptopyesyesyes
smartphoneyesyesyes
microwave with a timeryes — the time you setyes — it counts downyes
car engine controlleryes — sensor readingsyes — adjusts the fuel mixyes
a light switchnonono

The last row is the useful one. A device that only completes a circuit is not computing, however electrical it looks.

11. The screen is not the computer

Trap

The trap

The tempting picture. The monitor is the computer; the box under the desk is 'the hardware'; memory is where files live when you save them.

  • Puts the display at the centre, when it computes nothing
  • Confuses memory (RAM, temporary, holds the running program) with storage (a disk, permanent, holds files)
  • Leaves you unable to say what actually executes your instructions

This picture survives fine until Chapter 2, when a memory diagram asks you to draw a variable — and there is nowhere on your mental map to put it.

The fix

The picture that keeps working. The processor executes instructions; memory holds the data those instructions work on; everything else moves data to or from a human.

  • Processor = does the steps
  • Memory = holds the values while the steps run
  • Screen, keyboard, disk = input and output, at the edges

Every diagram in this book — memory diagrams, stack diagrams, references — is drawn inside the memory box. Getting that box in the right place now pays for itself repeatedly.

12. Sort the hardware by what it does

Sorting

Three jobs: computing, holding, and moving data to or from a human.

Sort into buckets

Put each component in the job it actually performs.

performs the computation
processor (CPU); a second processor core
stores data while it runs
memory (RAM)
moves data to or from a human
keyboard; monitor; touchscreen
compute
Processors execute the instructions. A machine with more cores has more of exactly this.
hold
Memory keeps values available to the processor while the program is running — and loses them when it stops.
edge
These are peripherals. They are how a person gets data in and results out; none of them computes.

13. Match the component to its one-line job

Matching

Say each pairing out loud as a sentence before you commit to it.

Match the pairs

  • p. processor
  • m. memory
  • s. screen
  • d. disk
  • r1. performs simple calculations, very fast
  • r2. temporarily stores information while a program runs
  • r3. displays results to a person
  • r4. keeps files after the power goes off

Why: The pairing worth dwelling on is memory against disk. Memory is temporary and fast and is where your running program's values live; a disk is permanent and slow and is where files live. Chapter 2 draws variables in memory, never on disk.

14. Why does the number of processors keep going up?

Socratic

Phones went from one processor to eight in about a decade, while the speed of a single processor barely moved.

Discussion prompt

If one processor performs calculations one after another, what does adding a second one let a machine do that a faster single processor would not? And what would it NOT help with?

Hint: Think about two jobs that do not depend on each other, versus one job whose every step needs the previous step's answer.

Answer:

A second processor lets independent work happen at the same time — decoding video while the browser lays out a page. It does nothing for a single chain of steps where each step needs the previous answer.

That distinction is worth banking now. Almost everything you write in this book is one such chain, executed by one processor, one statement after another — which is exactly why you can trace a program with a pencil.

15. What a program is made of

Section

Section 1.2

16. A program is a sequence of instructions

Concept

A program is a sequence of instructions that specifies how to perform a computation. The computation might be mathematical — solving equations, finding roots — or symbolic, like searching and replacing text in a document, or (strangely enough) compiling another program.

Figure (svg): Five boxes naming the basic instructions: input, output, math, decision and repetition

Believe it or not, that is pretty much all there is to it. Every program you have ever used, however complicated, is made of small instructions that look much like these.

17. Where this course teaches each of the five

Notation

This is not a list to memorise — it is a map of the next eight chapters. Each note points at the chapter where that instruction gets its own name in Java.

Annotate

  • output comes first — and it is the only one you can do today, which is why Hello World prints rather than calculates.
  • math arrives with variables in Chapter 2, because arithmetic is not much use until you can store the answer.
  • decision and repetition are the last two, and they are the two that make a program more than a list. Everything before them runs top to bottom, every time.
  • Notice how short the list is. Five ideas, spread over six chapters, and then you can write essentially anything.

If you ever feel lost later in the book, come back to this slide and ask which of the five you are looking at.

18. Breaking a task into the five instructions

Worked example

Programming, Think Java says, is the process of breaking a large task into smaller and smaller subtasks until each one is simple enough for the hardware. Do that once, by hand, for: print the average of five numbers a user types in.

Get five numbers from the user.

Why: That is input, five times — or once, repeated.

Keep a running total as each number arrives.

Why: That is math: addition.

Do the previous two steps five times rather than writing them five times.

Why: That is repetition.

Divide the total by five.

Why: math again: division.

Display the result.

Why: output.

Notice what is missing: nothing here checks a condition.

Why: This task needs no decision — four of the five instructions are enough.

Verify: Count the distinct instruction kinds you used: input, math, repetition, output — four.

Why: If you can name which of the five each step is, you can look up how to write it. That lookup is what the next five chapters are.

This is the whole method: decompose until each piece is one of five things you know how to write.

19. Which of the five is each statement?

Definition probe

You have not learned Java yet. Read them as English and classify.

Sort into buckets

Sort each described action into the kind of instruction it is.

input
read a temperature from a sensor
output
write the result into a file
math
add 1 to the running total
decision
if the total is over 100, stop
repetition
do the whole thing again for the next reading
in
Getting data from outside the program — a keyboard, a file, or a sensor — is input.
out
Sending data out of the program, to a screen or a file, is output. Note that a file can be either, depending on direction.
math
Arithmetic on values the program already holds.
dec
Anything that checks a condition and takes one path or another.
rep
Performing an action repeatedly, usually with some variation each time.

20. Why 'compiling a program' is itself a computation

Intuition

Think Java slips in a strange example: a computation might be compiling a program. It is worth stopping on, because it is the first hint that programs are just data.

the computationits inputits output
adding two numberstwo numbersone number
searching and replacing in a documenttext and two patternsnew text
compiling Hello.javayour source code, as textHello.class, as byte code

The compiler is a program whose input happens to be another program. Nothing special is going on — text goes in, a file comes out. You will meet javac doing exactly this in a few slides.

21. A decomposition that stops too early

Error analysis

Here is a student's plan for print the average of five numbers. It looks reasonable and it cannot be written, because two of its steps are not instructions the hardware can perform.

Annotate

  • Step 1 hides a repetition. 'The numbers' is five separate inputs. Until you say how many and how they arrive, there is nothing to write.
  • Step 2 is the whole problem restated. 'Average them' is not one of the five instructions — it is a name for a total-then-divide, which is math plus repetition.
  • Step 3 is fine. It is output, and it maps to one statement.
  • The test for 'decomposed far enough' is mechanical: can you name which of the five instructions each step is? Step 2 fails that test, so it is not done.

Decompose until every step has one of the five names. Not before, and — importantly — not after.

22. Order the subtasks by how close they are to code

Ranking

Decomposition goes from vague to writable. Put these five phrasings of the same task in order, vaguest first.

Put in order

  1. Make the program work out the average
  2. Read five numbers, then average them
  3. Read five numbers into a total, then divide the total by five
  4. Repeat five times: read a number, add it to total. Then divide total by 5.
  5. Repeat five times: input, then total = total + n. Then output total / 5.

Why: Each step names one more thing the hardware has to do. The last one is writable because every phrase in it is one of the five instructions — input, math, repetition, output. That is the finish line for decomposition: not elegance, just the point where each step has a name you can look up.

23. How many of the five does Hello World use?

Estimation

You have seen the program on the previous slide. Count before you scroll.

Predict first

How many of the five kinds of instruction does the Hello World program use?

  • Exactly one
  • Two
  • Three
  • All five

Correct: Exactly one

Why: Hello World performs output and nothing else — a single println. It takes no input, does no arithmetic, checks no condition and repeats nothing. That is precisely why it is the traditional first program: it exercises the smallest possible amount of the language while still proving your whole toolchain works.

24. Say the definition in your own words

Explain it to yourself

Close the slides for this one.

Discussion prompt

Write one sentence defining a program, without using the words 'sequence' or 'instructions'. Then check it against the book's version and note what you lost.

Hint: The two ideas you must keep: that there is more than one step, and that the order matters.

Answer:

The book's version: a program is a sequence of instructions that specifies how to perform a computation. The two load-bearing words are sequence (there is an order, and it matters) and specifies how (a program says the method, not just the goal).

Most rewrites drop the second one and end up describing a request rather than a program. Asking for the average is not a program; saying how to compute it is.

25. The Hello World program

Section

Section 1.3

26. Your first complete Java program

Concept

Traditionally, the first program you write in a new language displays the words Hello, World! on the screen. In Java it looks like this. Read it once without trying to understand every word — we will name every part over the next few slides.

public class Hello {
    public static void main(String[] args) {
        // generate some simple output
        System.out.println("Hello, World!");
    }
}
linewhat it is
public class Hello {a class definition begins
public static void main(String[] args) {a method definition begins — this is where the program starts
// generate some simple outputa comment; Java ignores it entirely
System.out.println("Hello, World!");a statement: display a line of text
} }the closing braces end the method, then the class

When this program runs it displays Hello, World! — note that the output does not include the quotation marks.

Downey & Mayfield, Think Java, 2nd edition (Green Tea Press / O'Reilly, 2020) — Think Java 2e, Chapter 1 (Computer Programming), Sections 1.1-1.4, pp. 1-6 — printed page 3

27. The three levels of a Java program

Picture it

Java programs are made of class and method definitions, and methods are made of statements. That is a strict nesting, and every program in this book has it.

Figure (svg): Three nested labels reading class, then method, then statement, each with its one-line job underneath

Read the arrow as contains: a class contains methods, a method contains statements. The curly braces in the source are how Java writes that containment down.

28. Naming every part of Hello World

Worked example

Go through the program once, slowly, naming each piece. By the end there should be no character you cannot account for.

public class Hello {
    public static void main(String[] args) {
        // generate some simple output
        System.out.println("Hello, World!");
    }
}
partnamewhat it does
Helloclass namenames the class; must match the filename Hello.java
mainmethod namespecial: execution starts at the first statement in main
String[] argsparameterhow the command line reaches the program (Chapter 9)
//comment markerJava ignores everything from here to the end of the line
System.out.printlna method calldisplays a line on the screen
;semicolonends the statement
{ }curly bracesgroup things together — outer pair the class, inner pair the method

Find the class definition.

Why: public class Hello opens it; the last } in the file closes it. A class, for now, is a collection of methods.

Find the method definition inside it.

Why: public static void main(String[] args) opens it. A method is a named sequence of statements.

Find the one statement inside the method.

Why: System.out.println("Hello, World!"); — a statement is a line of code that performs a basic action.

Account for the comment.

Why: The line starting // is a comment: English text explaining the code, with no effect on execution.

Account for the semicolon.

Why: Like most statements, the print statement ends with a semicolon.

Verify: Cover the slide and rebuild the program from the three words class, method, statement.

Why: If you can write the skeleton and only have to look up the exact spelling of System.out.println, you have the structure — and the structure is the part that transfers to every later program.

29. Rebuild the skeleton

Fill the middle

Every Java program in the next six chapters starts from exactly this shape.

Fill in the blanks

public class Hello main}(String[] args) println}("Hello, World!");
}
}

Why: class opens the class definition, main names the method the JVM starts at, and println is the method that displays a line. Those three words plus the braces are the skeleton — if you can type this from memory, you can start any program in this book without looking anything up.

30. The name of the class and the name of the file

Concept

One rule in this program is not a convention you can ignore — it is enforced by the compiler, and it is the single most common reason a beginner's first program refuses to compile.

Figure (svg): A rule card reading class Hello maps to the file Hello.java, with a note that the case must match

the class you wrotethe file it must be incompiles?
public class HelloHello.javayes
public class Hellohello.javano — case must match
public class HelloMain.javano — names must match
public class GreetingGreeting.javayes

You can give a class any name you like, but it is conventional to start with a capital letter — and the file name has to follow whatever you chose.

31. Java is case-sensitive, and it means it

Trap

The trap

What a beginner types, having read the program once rather than copied it.

public class hello {
    public static void Main(String[] args) {
        system.out.println("Hello, World!");
    }
}
what is wrongwhat happens
hello lowercasecompiles, but the file must then be hello.java — and convention is broken
Main capitalisedcompiles, but it is not main, so the program has no entry point and will not run
system lowercasedoes not compile: there is no class called system

Two of these three produce a program that compiles and then fails to do anything, which is far more confusing than a compiler error.

The fix

What it has to be. System with a capital S, main with a lowercase m.

public class Hello {
    public static void main(String[] args) {
        // generate some simple output
        System.out.println("Hello, World!");
    }
}
tokenwhy the case is what it is
Systema class from the Java library; class names start with a capital
outa field inside System; fields start lowercase
printlna method; method names start lowercase
mainthe entry point the JVM looks for — spelled exactly this way

Think Java states it plainly: uppercase and lowercase are not the same. System has to begin with an uppercase letter; system and SYSTEM will not work.

32. Which line is the statement?

Elimination

A statement is a line of code that performs a basic action. Only one of these qualifies.

Eliminate the wrong options

Rule out everything that is not a statement, and keep the one that is.

  • A. public class Hello {
  • B. public static void main(String[] args) {
  • C. // generate some simple output
  • D. System.out.println("Hello, World!");

Survives elimination: D

Why: Only the println line performs a basic action — it displays a message. The two definitions build the structure that holds statements, and the comment is invisible to Java. The semicolon is a good tell: most statements end with one, and definitions opening a block end with a brace instead.

33. What exactly appears on the screen?

Prediction

Read the println line carefully. The answer trips up more people than it should.

System.out.println("Hello, World!");
part of the linedoes it appear in the output?
System.out.printlnno — it is the instruction, not the data
the quotation marksno — they mark where the text starts and ends
Hello, World!yes — this is the data
the semicolonno — it ends the statement

Predict first

What does the screen show when this statement runs?

  • Hello, World!
  • "Hello, World!"
  • System.out.println("Hello, World!")
  • Hello, World!;

Correct: Hello, World!

Why: The output does not include the quotation marks. Quotes delimit the text in your source — they tell the compiler where the string begins and ends — and they are not part of the data itself. This is the first instance of a distinction that runs through the whole course: the notation you write is not the value you get.

34. What is String[] args for?

Missing information

You have accounted for every part of the program except one, and Think Java deliberately postpones it.

Discussion prompt

main takes a parameter called args. Nothing in Hello World uses it. What information would you need before you could say what it is for — and why do you think the book leaves it until Chapter 9?

Hint: Where could data come from, if the program has not asked the user for anything yet?

Answer:

args holds command-line arguments — the words you type after the program's name when you run it. java Hello world would put world into args.

The book postpones it because it is an array of Strings, and both of those are chapters away (arrays in Chapter 7, immutable Strings in Chapter 9). This is Think Java's stated method: explain a feature briefly when it first appears, then properly later. Being able to say 'that part is real, and I will meet it in Chapter 9' is a useful skill in itself.

35. Reading the program line by line

Section

Section 1.3, continued

36. Braces group, semicolons end, slashes hide

Concept

Three pieces of punctuation carry almost all of Java's structure. They are worth learning as a set, because every compile error you hit in the next month will involve one of them.

Figure (svg): Three punctuation marks with their jobs: braces group, semicolon ends a statement, double slash hides the rest of the line

punctuationjobin Hello World
{ }group things togetherouter pair holds the class, inner pair holds the method
;end a statementafter the println call
//start a commentbefore 'generate some simple output'
" "delimit a piece of textaround Hello, World!
( )hold a method's parameters or argumentsaround String[] args, and around the text to print

Java uses curly braces to group things together. In Hello.java the outermost braces contain the class definition, and the inner braces contain the method definition.

37. Every character of Hello World, annotated

Notation

This is the slide to come back to. Nothing in the program is decorative — each mark is doing one job.

Annotate

  • public — for now, take it on faith. It says this class and method are visible from outside. It matters in Chapter 11; today it is boilerplate you copy.
  • class Hello — names the class. This name must match the file name, Hello.java, exactly, including case.
  • static — again, boilerplate for now. It says main belongs to the class rather than to an object, which is only meaningful once objects exist (Chapter 10).
  • void — this method returns nothing. Chapter 4 introduces methods that do return something, and this word changes.
  • main — the special one. When the program runs, it starts at the first statement in main and ends when it finishes the last.
  • // comment — English for a human. Java ignores it from the slashes to the end of the line. Comments have no effect on execution, but they make it easier for other programmers — including your future self — to understand what you meant.
  • System.out.println(...) — reads as: in the class System, take the field out, and call its method println. Chapter 3 unpacks the dots properly.
  • ; — ends the statement. Missing it is the single most common compile error you will meet.

Four of these — public, static, void, and the dots in System.out — are explained later. Copying them correctly now while knowing they are placeholders is the right way to use this program.

38. Adding a second statement

Worked example

The cheapest way to test whether you have understood the structure is to add something to it. Put a second line of output in, and watch what does and does not change.

public class Hello {
    public static void main(String[] args) {
        // generate some simple output
        System.out.println("Hello, World!");
        System.out.println("How are you?");
    }
}
stepwhat runsscreen so far
1enter main(nothing)
2the comment — skipped entirely(nothing)
3println("Hello, World!")Hello, World!
4println("How are you?")Hello, World!\nHow are you?
5reach the closing brace of main — the program endsHello, World!\nHow are you?

Add the new statement inside the inner braces.

Why: It has to be inside main, because that is the sequence of statements that runs.

End it with a semicolon.

Why: Like most statements, a print statement ends with a semicolon.

Do not add any braces.

Why: The structure has not changed — still one class, one method. Only the number of statements changed.

Predict the order before running.

Why: Statements in a method run top to bottom. The first println runs first.

Verify: Compile and run it; expect exactly two lines, in the order they appear in the source.

Why: If the lines came out in the other order, you would have discovered something remarkable — which is a useful reminder that in this book, execution order is source order until Chapter 5 gives you a way to change it.

39. Which statement about comments survives?

Two truths and a lie

Three claims about the // line. Two are false.

Eliminate the wrong options

Eliminate the false claims and keep the true one.

  • A. The comment makes the program run slightly slower.
  • B. Java ignores everything from // to the end of the line.
  • C. Removing the comment would change the program's output.
  • D. A comment must appear on its own line.

Survives elimination: B

Why: When Java sees // it ignores everything from there until the end of the line. That single rule explains all three false claims: nothing survives to slow the program down, nothing reaches the output, and a comment can start anywhere on a line because it only runs to that line's end.

40. Why comments exist at all

Intuition

A comment has no effect on execution. Deleting every comment from a program changes nothing about what it does. So why write them?

Figure (svg): Two panels comparing the print statement alone against the same statement preceded by an explanatory comment

Think Java's answer: comments make it easier for other programmers — and your future self — to understand what you meant to do. Note the phrasing: what you meant, which is exactly the thing the code cannot tell you, because the code only says what it does.

41. Four ways to break Hello World

Error analysis

Each of these is one character different from a working program. Read the annotations and predict the compiler's complaint before you look.

Annotate

  • Line 3 has no semicolon. The compiler reads on, looking for the end of the statement, and complains at the } on line 4 — so the error message points at a line that is perfectly fine. Expect this: the reported line is often just after the real one.
  • If you also deleted line 5's brace, the class would never close, and the message would be about reaching the end of the file unexpectedly.
  • If you wrote println("Hello, World!") without System.out., the compiler would say it cannot find a method called println — because on its own, there is no such thing in scope.
  • If you opened the quote and never closed it, the error is about an unclosed string literal, and it is reported on the right line — string errors are the friendly ones.

The lesson is not the four messages. It is that the line the compiler names is where it noticed, not always where you erred — so read upward from the reported line.

42. Match each piece of punctuation to its job

Translation

Five marks, five jobs. Do this from the structure rather than by memory.

Match the pairs

  • b. { }
  • s. ;
  • c. //
  • q. " "
  • p. ( )
  • r1. group a class or a method's contents together
  • r2. mark the end of a statement
  • r3. hide the rest of the line from Java
  • r4. mark where a piece of text starts and ends
  • r5. hold a method's parameters or arguments

Why: Braces group, semicolons end, slashes hide, quotes delimit text, parentheses hold arguments. Every compile error in your first month will be a missing or mismatched one of these five, so being able to name the job makes the error message readable.

43. Can a Java program have no statements?

Counterexample

Push on the structure to find its edges.

Discussion prompt

Hello World is a class containing a method containing one statement. Could you write a legal Java program with a class and a main method but zero statements inside main? What would it do?

Hint: Ask what the braces require, versus what they merely allow.

Answer:

Yes. public class Hello { public static void main(String[] args) { } } compiles and runs perfectly. It starts at main, finds nothing to do, and ends.

That is worth knowing for a practical reason: it is the smallest program that proves your toolchain works. If it compiles and runs without complaint, javac and java are installed and talking to each other, and any later failure is your code rather than your setup.

44. Definition or statement?

Discrimination

The distinction is structural: a definition builds the container, a statement performs an action inside it.

Sort into buckets

Sort each line by what it is.

a definition
public class Hello {; public static void main(String[] args) {
a statement
System.out.println("Hi");; System.out.println("Bye");
neither — Java ignores it
// a note to myself
def
Class and method definitions declare structure. They open a block with a brace rather than ending with a semicolon.
stmt
A statement is a line of code that performs a basic action, and most of them end with a semicolon.
none
A comment is neither. Java discards it, so it is not part of the program's structure or its behaviour.

45. Compiling and running

Section

Section 1.4

46. Java is compiled AND interpreted

Concept

Java is a high-level language — readable by people, portable across machines. Hardware only executes low-level machine language. Something has to translate, and Java's answer is unusual: it does both kinds of translation.

Figure (svg): Five stages: Hello.java as source, javac the compiler, Hello.class as byte code, java interpreting it, then output

compiler — Reads the entire program and translates it completely before the program starts running.

interpreter — Reads a high-level program and executes it a little at a time, alternately reading and computing.

source code — The high-level program you write — Hello.java.

byte code — The code javac produces for the virtual machine — Hello.class. Looks like object code, easy and fast to interpret.

47. Why the virtual machine is worth the extra step

Picture it

Object code is not portable: you cannot run an executable compiled for a Windows laptop on an Android phone. Compiling for an imaginary machine instead is how Java gets around that.

Figure (svg): Two panels: compiling separately for Windows, Android and macOS, against compiling once to byte code that any JVM runs

That is the trade: one extra translation step at run time, in exchange for compiling once and running the same file on machines that share no hardware at all.

48. Compiling and running Hello.java at the command line

Worked example

Most development environments hide these two commands behind a button. Run them by hand once, so that when the button fails you know which half broke.

$ javac Hello.java
$ java Hello
Hello, World!
commandreadsproduces
javac Hello.javaHello.java (your source)Hello.class (byte code)
java HelloHello.class (byte code)output on the screen

Save the program in a file named Hello.java.

Why: The file name must match the class name — this is checked by the compiler.

Run javac Hello.java.

Why: javac is the Java compiler. It translates .java files into .class files that store the resulting byte code.

If there are no errors, look for a new file: Hello.class.

Why: Silence from javac means success. It prints nothing when it works — which surprises people.

Run java Hello — with no extension.

Why: java is the Java interpreter, short for Java Virtual Machine. You name the CLASS, not the file, so there is no .class on the end.

Verify: Expect exactly Hello, World! and a new Hello.class file in the directory.

Why: If javac printed nothing at all, that is success. If java complains it cannot find or load the main class, you almost certainly typed java Hello.class instead of java Hello.

49. What does javac print on success?

Hypothesis

This catches almost everyone once, because every other tool you have used announces that it worked.

Predict first

You run javac Hello.java on a correct program. What appears in the terminal?

  • Nothing at all
  • A success message naming the output file
  • The compiled byte code
  • Hello, World!

Correct: Nothing at all

Why: javac says nothing when it succeeds — silence is the success message, and a new Hello.class file is the only evidence. It does not run your program, so 'Hello, World!' cannot appear yet; that needs the second command, java Hello. Expecting output here is why people run javac twice and wonder why nothing happens.

50. Which command failed?

Concept

Knowing the two steps turns a single confusing failure into two much easier questions. When something goes wrong, first ask which command produced the message.

symptomwhich stepwhat it means
javac prints an error mentioning a line numbercompileYour source is not legal Java. Nothing ran; there is no .class file yet.
javac prints nothingcompileSuccess. Look for Hello.class.
'class Hello is public, should be declared in a file named Hello.java'compileThe class name and file name do not match.
'Could not find or load main class'runIt compiled fine. You are naming the class wrongly, or you are in the wrong directory.
The program runs and prints the wrong thingneitherBoth steps worked. This is a logic error — your instructions were legal but not what you meant.

That last row is the important one, and Chapter 1 ends on it: a program can be perfectly legal and still be wrong. Compiling is not the same as being correct.

51. java Hello.class is not the command

Trap

The trap

The natural guess. You just made a file called Hello.class, so you try to run it.

$ javac Hello.java
$ java Hello.class
Error: Could not find or load main class Hello.class
what you typedhow java read itresult
java Hello.classlook for a class named Hello.classno such class — the dot is read as a package separator
java Hellolook for a class named Hellofound; runs main

The error message is honest but unhelpful: it really is looking for a class whose name it thinks is Hello.class, because in Java a dot separates package names.

The fix

The rule. javac takes a file name (with .java); java takes a class name (with no extension at all).

$ javac Hello.java
$ java Hello
Hello, World!
commandargument is a...example
javacfile name, with extensionjavac Hello.java
javaclass name, no extensionjava Hello

One takes a file, the other takes a class. Said once, this sticks — and it removes what is probably the single most common first-day error.

52. Compiled, interpreted, or both

Trade off

Fill in the blank cells from what the chapter says. This is the table that explains Java's design choice.

Comparison matrix

approachtranslate when?portable?typical speed
pure interpretera little at a time, while runningyes — the source travelsslower
pure compilerall of it, before runningno — object code is machine-specificfaster
Javacompile to byte code, then interpret ityes — byte code runs on any JVMfast, after a small start-up cost

Java takes the portability of an interpreter and most of the speed of a compiler, at the cost of requiring a JVM to be installed on the target machine.

53. Put the toolchain in order

Ranking

From typing to seeing output. Five steps.

Put in order

  1. You write source code in Hello.java
  2. javac translates it
  3. Hello.class, holding byte code, appears
  4. java (the JVM) interprets the byte code
  5. Hello, World! is displayed

Why: Source, compile, byte code, interpret, output. The step people leave out is the middle one — Hello.class is a real file on disk, and being able to point at it is what makes the two commands make sense rather than being a ritual.

54. Could you run Hello.class on a phone?

Edge cases

Push the portability claim until it breaks.

Discussion prompt

You compile Hello.java on a Windows laptop and copy the resulting Hello.class to an Android phone. Under what condition does it run — and what exactly is it that has to be portable?

Hint: The byte code is the same on both machines. What has to differ?

Answer:

It runs provided the phone has a JVM — a Java interpreter built for that machine. The byte code is identical on both; what differs is the interpreter reading it.

So Java's portability claim is precise rather than magical: the byte code is portable, the virtual machine is not. Someone has to write and ship a JVM for each kind of hardware, and once they have, every Java program in the world runs there without being recompiled.

55. Source code, byte code, machine code

Comparison

Three kinds of code appeared in this lesson and it is easy to blur them. Fill the blanks from what you have seen.

Comparison matrix

source codebyte codemachine code
the fileHello.javaHello.class(never a file you make in Java)
who reads ityou, and javacthe JVM (java)the processor itself
portable?yesyes — any machine with a JVMno — one kind of machine only
readable by a person?yes, that is the pointbarely — it looks like object codeno

The row that matters is the third. Portability is the reason the middle column exists at all.

56. The pattern to carry away

Pattern

Every program in the next six chapters is this shape, with more statements inside main. Learn the skeleton now and you never spend attention on it again.

public class Name {
    public static void main(String[] args) {
        // statements go here, and run top to bottom
    }
}
you changeyou never change (yet)
the class name — and the file name to matchpublic static void main(String[] args)
the statements inside mainthe two pairs of braces
how many statements there arethat execution starts at the first statement in main

57. Check: the file name rule

Check

Work it out before you click.

Check your understanding

You write public class Greeting { ... }. What must the file be called?

  • A. Greeting.java (correct)
  • B. greeting.java
  • C. Greeting.class
  • D. Main.java

Answer: A

Why: The name of the class has to match the name of the file it is in, and Java is case-sensitive, so a class named Greeting must live in Greeting.java. This is enforced by the compiler, not merely a convention.

Why B tempts people
The case must match too. greeting.java does not match class Greeting, and javac will say so explicitly.
Why C tempts people
.class is what javac produces, not what you write. You write .java source and the compiler emits .class byte code.
Why D tempts people
The file name follows the class name you chose. Calling it Main.java would require the class to be named Main.

58. Check: the order of the commands

Check

Work it out before you click.

Check your understanding

Which pair of commands compiles and then runs Hello.java?

  • A. javac Hello.java then java Hello (correct)
  • B. java Hello.java then javac Hello
  • C. javac Hello then java Hello.class
  • D. java Hello then javac Hello.java

Answer: A

Why: javac is the compiler and takes the file name including its .java extension; java is the interpreter and takes the class name with no extension. Compiling has to happen first, because java needs the .class file that javac produces.

Why B tempts people
This reverses the two tools. java interprets byte code and cannot read your source file, and compiling after running is too late to help.
Why C tempts people
Both arguments are wrong: javac needs Hello.java with the extension, and java needs Hello without one.
Why D tempts people
The order is backwards. There is no .class file to run until javac has produced one.

59. Check: what actually appears

Check

Work it out before you click.

public class Test {
    public static void main(String[] args) {
        // System.out.println("first");
        System.out.println("second");
    }
}
lineruns?
// System.out.println("first");no — the whole line is a comment
System.out.println("second");yes

Check your understanding

What does this program display?

  • A. second (correct)
  • B. first
    second
  • C. first
  • D. Nothing — it will not compile

Answer: A

Why: The first println has been commented out. When Java sees // it ignores everything to the end of that line, so the statement never runs and only 'second' is displayed. Commenting out a line is the standard way to disable code temporarily without deleting it.

Why B tempts people
This assumes both lines run, but the first is hidden behind // and is discarded by the compiler.
Why C tempts people
This has it backwards — the commented line is the one that does NOT run.
Why D tempts people
The program is perfectly legal. A commented-out statement is not an error; it is simply absent.

60. Where the two-step build shows up later

Real world

javac and java look like a beginner's chore. They are the smallest instance of something you will meet for the rest of your career.

Discussion prompt

Think of any app on your phone. Someone wrote source code; you are running something else. Where do you think the compile step happened, and what would have to be true for the same app to run on a different phone?

Hint: You never received the source code. What did you receive?

Answer:

The compile happened on the developer's machine or a build server, long before you downloaded anything. You received the compiled artifact, not the source.

For it to run on a different phone, either it was compiled again for that hardware, or — Java's answer — it was compiled once into a portable intermediate form that each device's own runtime interprets. Android took exactly this route, which is why Java's design decision from the 1990s is still on a billion devices.

The transferable idea: whenever you meet a new toolchain, ask what the two steps are — what turns your text into an artifact, and what runs the artifact. Almost every language has that seam somewhere.

61. How sure are you?

Commit first

Commit to an answer and to how confident you are. Both are informative.

Predict first

A program compiles with no errors at all. Does that mean it will produce the output you intended?

  • Yes — compiling means it is correct
  • No — it only means the program is legal Java
  • Only if it has no comments
  • Only if it has exactly one class

Correct: No — it only means the program is legal Java

Why: The compiler checks that your program obeys the rules of the language, not that it does what you meant. A program that prints the wrong thing, or divides when it should multiply, compiles perfectly. Think Java names this a logic error, and the whole of Section 1.9 and Appendix D exist because of it. Compiling is a floor, not a ceiling.

62. Explain it to someone else

Explain it

Explaining out loud is the fastest way to find the part you only half know.

Discussion prompt

In sixty seconds, explain to someone who has never programmed what happens between you pressing 'run' and 'Hello, World!' appearing. You must use the words source code, compiler, byte code and virtual machine, and you may not read from the slides.

Hint: Five nouns, in order: file, compiler, file, interpreter, screen.

Answer:

A version that works: I write source code in Hello.java. The compiler, javac, reads all of it and translates it into byte code, which it saves in Hello.class. Byte code is not for my computer exactly — it is for an imaginary machine. So a program called java, the virtual machine, reads the byte code and does what it says, and that is when the text appears.

If you found yourself stuck on why the imaginary machine exists, that is the part to reread: it is the portability argument, and it is the only reason Java has two steps instead of one.

63. Exit ticket

Exit ticket

One question. Answer it before you close the deck.

Predict first

In one sentence: what is the difference between what javac produces and what java consumes?

  • Nothing — they are the same file, Hello.class
  • javac produces source code; java consumes byte code
  • javac produces machine code; java consumes source code
  • javac produces Hello.java; java consumes Hello.class

Correct: Nothing — they are the same file, Hello.class

Why: This is the point of the two-step model: javac's output IS java's input. javac reads Hello.java and writes Hello.class; java reads that same Hello.class and executes it. Seeing the two commands as joined by one file on disk — rather than as a ritual — is what makes build errors diagnosable, because you can always ask which of the two steps the file got to.

64. Draw the whole lesson

Connect it up

One picture, from memory, before you leave.

Draw it

Draw the path from your keyboard to the words on the screen. Label: Hello.java, javac, Hello.class, java, output. Then, off to one side, draw the Hello World program and label the class, the method, the statement and the comment. Finally, circle the one place in your drawing where a logic error could hide.

65. Recap

Recap

Four sections, one program, two commands. Everything after this builds on the skeleton you can now write from memory.

if you remember one thingit is this
about structureclass contains method contains statement
about the toolchainjavac takes a file, java takes a class
about being finishedit compiled is not it works

Sources

  1. Downey & Mayfield, Think Java, 2nd edition (Green Tea Press / O'Reilly, 2020) — Think Java 2e, Chapter 1 (Computer Programming), Sections 1.1-1.4, pp. 1-6
  2. The Java Tutorials — Getting Started: The 'Hello World!' Application
  3. Think Java 2e — free online edition and source code

Want this taught 1-on-1? Alexander tutors Java — $55/session, free consultation.

Book on Wyzant · Text (657) 465-8108