Putting several statements in main, the difference between print and println, which spaces Java actually requires, the four escape sequences worth memorising, and why deliberately breaking your own program is a study technique rather than a waste of time. Follows Think Java 2e, Chapter 1 (Computer Programming), Sections 1.5-1.9, pp. 6-12, cross-referenced against The Java Tutorials — Characters (escape sequences).
Subject: Java · 65 slides · code lesson
Open the interactive version of this deck
Title
Think Java 2e · Chapter 1 · Computer Programming
Sections 1.5-1.9 · pp. 6-12
Objectives
This lesson follows Think Java 2e, Chapter 1 (Computer Programming), Sections 1.5-1.9, pp. 6-12. Everything on these slides can be checked against those pages.
1. Put several statements in main and predict the exact output, including where the line breaks fall.
2. Say what println appends that print does not, and choose between them deliberately.
3. Point at the spaces in a Java program that are required and the ones that are only for human readers.
4. Write the four common escape sequences and explain why a backslash is needed to put a quote inside a string.
5. Define algorithm, bug and debugging in the book's own terms.
6. Describe debugging as a hypothesis-and-test loop, and say what to do when a hypothesis turns out wrong.
Warm-up
One minute, from memory. Lesson 1a is the only thing you need.
Discussion prompt
Without scrolling back: write out the Hello World program from memory. Then name the two commands that compile it and run it, and say which one takes a file name and which takes a class name.
Hint: class, method, statement — then javac and java.
Answer:
public class Hello { public static void main(String[] args) { System.out.println("Hello, World!"); } } — then javac Hello.java (a file name, with the extension) and java Hello (a class name, without one).
Everything in this lesson is a small change to that program. If the skeleton is not yet automatic, the changes will be harder to see, so it is worth the minute.
Concept
This lesson takes Hello World and changes it four times: more statements, a different print method, different whitespace, and special characters inside the string. Each change isolates exactly one idea — which is itself the technique the last section of the chapter recommends.
Figure (svg): Four boxes showing the four changes made to Hello World: more statements, print versus println, whitespace, and escape sequences
Downey & Mayfield, Think Java, 2nd edition (Green Tea Press / O'Reilly, 2020) — Think Java 2e, Chapter 1 (Computer Programming), Sections 1.5-1.9, pp. 6-12 — Sections 1.5-1.9, printed pages 6-12.
Section
Section 1.5
Concept
You can put as many statements as you like in the main method. They run in the order they are written, top to bottom. This example also shows something new: a comment can sit at the end of a line, not only on a line of its own.
public class Hello2 {
public static void main(String[] args) {
// generate some simple output
System.out.println("Hello, World!"); // first line
System.out.println("How are you?"); // another line
}
}| order | statement | what appears |
|---|---|---|
| 1 | println("Hello, World!") | Hello, World! |
| 2 | println("How are you?") | How are you? |
| — | the two // comments | nothing — Java ignores them |
Note the trailing comments. When Java sees // it ignores to the end of that line — so a comment after a statement is legal, and the statement before it still runs.
Picture it
Until Chapter 5 gives you a way to change it, this is the whole story of control flow: one statement after another, in the order you wrote them.
Figure (svg): A pipeline showing entry into main, then two println statements in order, then the end of the program
Because there are no branches, you can predict this program's output exactly, every run. Hold on to that certainty — it is what makes tracing by hand possible, and it is what Chapter 5 will complicate.
Worked example
The habit worth building today: say what you expect, then run it. A prediction that turns out wrong is worth far more than a program that happens to work.
public class Order {
public static void main(String[] args) {
System.out.println("one");
// System.out.println("two");
System.out.println("three");
}
}| line | runs? | output line |
|---|---|---|
| println("one") | yes | one |
| // println("two") | no — commented out | (none) |
| println("three") | yes | three |
Read top to bottom and mark each statement as live or commented.
Why: Only the // line is dead; the slashes hide the rest of that line from Java.
Write the expected output on paper before compiling.
Why: Two lines: one then three.
Notice what is NOT in the output.
Why: two never appears, and there is no blank line where it would have been — a commented statement leaves no trace at all.
Verify: Compile and run; expect exactly two lines, one and three.
Why: If a blank line appeared between them, you would have found a real bug in your understanding — a commented-out println prints nothing whatsoever, not an empty line.
Prediction
Count carefully; one of these statements is not what it appears.
System.out.println("A");
// System.out.println("B");
System.out.println("C"); // System.out.println("D");| statement | live? |
|---|---|
| println("A") | yes |
| println("B") | no — whole line commented |
| println("C") | yes |
| println("D") | no — it is inside a trailing comment |
Predict first
How many lines does this fragment display?
Correct: 2
Why: Only A and C run. B is commented out on its own line, and D sits inside a trailing comment — once Java sees // it ignores everything to the end of that line, including something that looks like a complete statement. A commented statement is not a shorter statement; it is no statement at all.
Concept
Section 1.5 slips in a second comment style without making a fuss about it. Both are the same //; the only difference is what precedes them on the line.
| style | example | when to use it |
|---|---|---|
| on its own line | // generate some simple output | explaining the block of code that follows |
| at the end of a line | System.out.println("Hi"); // first line | a short note about that one statement |
| (not a comment) | System.out.println("// hi"); | inside quotes it is just text — it prints |
The third row is worth pausing on. // only starts a comment when Java is reading code; inside a string it is two ordinary characters, and they will appear in the output.
Trap
The assumption. // always means 'ignore the rest of the line'.
System.out.println("Visit http://example.com");| expected by the assumption | what actually happens |
|---|---|
| Java ignores from the first // onward | the // is inside quotes, so it is ordinary text |
output: Visit http: | output: Visit http://example.com |
| the statement is broken | the statement is perfectly fine |
If the rule really were 'always ignore', this line would not even compile — the string would never be closed. It compiles and prints the whole URL.
The rule, stated precisely. // starts a comment only where Java is reading code. Inside a string literal, every character is data.
System.out.println("Visit http://example.com"); // a real comment| the // in question | code or data? | effect |
|---|---|---|
| inside the quotes | data | printed as part of the text |
| after the semicolon | code | starts a comment; ignored |
This distinction — is the compiler reading code, or reading data? — comes back for every special character in this lesson, and it is the whole reason escape sequences exist.
Socratic
A question about what you are relying on when you predict output.
Discussion prompt
You predicted the output of a three-statement program with complete confidence. What property of the program made that possible, and can you think of a kind of program where it would not be?
Hint: What would have to be in the program for the output to differ between two runs?
Answer:
The property is that the program is a straight sequence — no decisions, no repetition, no input. Given the same source you get the same output, every time.
A program that reads input (Chapter 3) or checks a condition (Chapter 5) loses that. Then the output depends on something outside the source, and predicting it means tracing with a specific input in mind. That is exactly why tracing tables appear on nearly every slide from Chapter 3 onward.
Fill the middle
Extend the program without changing its structure.
Fill in the blanks
public class Three println}("second");
System.out.println("third");
}
}
Why: The method is println and the statement ends with a semicolon. Nothing about the class or the method changes when you add statements — you only ever add lines inside the inner braces. That is what makes the skeleton worth memorising once.
Explain it to yourself
Say it precisely, in one sentence.
Discussion prompt
Write a one-sentence rule describing the order in which the statements in a main method run. Make it precise enough that someone could use it to predict output without running anything.
Hint: Two things need saying: where execution starts, and what happens next.
Answer:
Something like: execution begins at the first statement in main and proceeds to the next statement in source order until main's last statement finishes, at which point the program ends.
The clause people leave out is the ending. A program stops when main runs out of statements — not when the file ends, and not when the last class closes. That distinction starts to matter as soon as there is more than one method, in Chapter 4.
Section
Section 1.5, continued
Concept
System.out.println appends a special character, called a newline, that moves to the beginning of the next line. If you do not want a newline at the end, use print instead.
public class Goodbye {
public static void main(String[] args) {
System.out.print("Goodbye, ");
System.out.println("cruel world");
}
}| statement | text sent | newline added? | cursor ends |
|---|---|---|---|
| print("Goodbye, ") | Goodbye, | no | just after the space |
| println("cruel world") | cruel world | yes | start of the next line |
Because the first statement adds no newline, the output appears on a single line: Goodbye, cruel world. Notice the space at the end of the first string — it is what separates the two words, and without it the output would read Goodbye,cruel world.
Picture it
The clearest way to think about print and println is as a cursor moving across the screen. Each call writes text at the cursor; only println then moves it to the next line.
Figure (svg): A trace strip showing the output line building up: Goodbye, then Goodbye, cruel world, then the cursor moving to the next line
The underscore is the cursor. Reading print and println this way makes the next few slides — where the newline moves into the middle of a string — much easier to predict.
Worked example
Use print deliberately: assemble a single line of output from three separate statements, then close it.
public class Line {
public static void main(String[] args) {
System.out.print("2");
System.out.print(" + ");
System.out.print("2");
System.out.println(" = 4");
}
}| statement | output so far |
|---|---|
| print("2") | 2 |
| print(" + ") | 2 + |
| print("2") | 2 + 2 |
| println(" = 4") | 2 + 2 = 4 (then a newline) |
Use print for every piece that should stay on the line.
Why: print sends the text and leaves the cursor where it is.
Watch the spaces inside the quotes.
Why: + has a space on each side. Java adds nothing between calls — every space you see in the output is one you typed.
Use println for the last piece only.
Why: That ends the line once, cleanly, rather than four times.
Verify: Run it and expect exactly one line: 2 + 2 = 4.
Why: If the pieces came out on four separate lines you used println throughout; if the words ran together you left the spaces out of the strings.
This is a real technique, not a curiosity — it is how you print a table row or a progress line later on.
Prediction
Two prints and one println.
System.out.print("a");
System.out.print("b");
System.out.println("c");| call | newline appended? |
|---|---|
| print("a") | no |
| print("b") | no |
| println("c") | yes |
Predict first
How many lines of output, and what do they contain?
Correct: One line: abc
Why: Only println appends a newline, and there is exactly one of those, at the end. The three pieces of text land side by side with nothing between them, because Java inserts nothing of its own — every space in output is a space you put inside a string.
Concept
Phrases that appear in quotation marks are called strings, because they contain a sequence of characters strung together in memory. Characters can be letters, numbers, punctuation marks, symbols, spaces and tabs.
Figure (svg): The string Goodbye, with each character in its own numbered box, showing that the trailing space is a character too
string — A sequence of characters strung together in memory; written in source code inside double quotation marks.
character — One letter, digit, punctuation mark, symbol, space or tab — a single element of a string.
Counting the space as a character is not pedantry. It is the difference between Goodbye, cruel and Goodbye,cruel, and it will matter a great deal in Chapter 6 when you start indexing into strings.
Trap
The attempt. Trying to build one line, but reaching for the familiar method each time.
System.out.println("2");
System.out.println(" + ");
System.out.println("2");
System.out.println(" = 4");| statement | newline? | result |
|---|---|---|
| println("2") | yes | line 1: 2 |
| println(" + ") | yes | line 2: + |
| println("2") | yes | line 3: 2 |
| println(" = 4") | yes | line 4: = 4 |
Four lines instead of one, and the leading spaces now look like stray indentation.
The fix. print for everything that stays on the line; println once, at the end.
System.out.print("2");
System.out.print(" + ");
System.out.print("2");
System.out.println(" = 4");| statement | newline? | result |
|---|---|---|
| print("2") | no | 2 |
| print(" + ") | no | 2 + |
| print("2") | no | 2 + 2 |
| println(" = 4") | yes | 2 + 2 = 4, line ended |
The rule to say out loud: println ends a line; print continues one. Choosing between them is a decision about layout, and it should be a deliberate one.
Discrimination
For each goal, decide which method the last call should use.
Sort into buckets
Sort each situation by the method it calls for.
Error analysis
A student expects Goodbye, cruel world and gets Goodbye,cruel world. The annotations locate the missing character.
Annotate
"Goodbye, ". Putting the space outside the quotes, in the source, does nothing at all — that space is formatting for you, not data.Bugs of exactly one character are the common case, not the exception. Learning to look for them is the point of Section 1.9.
Reverse engineer
You are shown output and must reconstruct the source. This is the reverse of what you have been doing, and it is a much better test of understanding.
Fill in the blanks
System.out.print("Total: ");
System.out.println("42");
Why: The output is a single line reading Total: 42, so the first call must not end the line — that is print — and the second one should, which is println. Reading output backwards to source is exactly the skill debugging requires, because a bug report gives you the output and asks for the cause.
Section
Section 1.6
Concept
In Java source code, some spaces are required — you need at least one between words. Most other spaces, and all the newlines, are optional. This program is not legal, because the words have run together:
publicclassGoodbye{
publicstaticvoidmain(String[] args) {
System.out.print("Goodbye, ");
System.out.println("cruel world");
}
}| what was removed | legal? | why |
|---|---|---|
| the spaces between public, class and Goodbye | no | publicclassGoodbye is a single word to Java, and it means nothing |
| the spaces inside String[] args | kept | the example leaves these in — they are between words too |
| the newlines | would be legal | newlines are optional; see the next slide |
The rule is about words, not about tidiness: Java needs to be able to tell where one word ends and the next begins.
Picture it
All three of these compile to exactly the same byte code. Only one of them is something you would want to open again tomorrow.
Figure (svg): Two panels comparing a program spread over many lines against the same program crushed onto three lines
Think Java's verdict on the right-hand version: it still works, but the program is getting harder and harder to read. Newlines and spaces are important for visually organising your program, making it easier to understand and to find errors when they occur.
Worked example
A mechanical test you can apply to any space in a Java program, without memorising a list of rules.
public static void main(String[] args) {| the space | between | required? |
|---|---|---|
| public_static | two words | yes |
| static_void | two words | yes |
| void_main | two words | yes |
| main_( | a word and a punctuation mark | no |
| String[]_args | two words | yes |
| )_{ | two punctuation marks | no |
Look at the two things the space separates.
Why: Ask what kind each one is: a word (letters and digits) or a punctuation mark.
If both sides are words, the space is required.
Why: Without it Java reads them as one longer word, which is not the word you meant.
If either side is punctuation, the space is optional.
Why: A bracket or a brace already marks the boundary, so no space is needed to find it.
Apply it to the illegal example.
Why: publicclassGoodbye puts three words together with no punctuation between them — so at least two spaces were required, and both were removed.
Verify: Test the rule on System.out.println — can you remove the dots' surrounding spaces? There are none to remove, and the dots are punctuation, so no space was ever needed.
Why: The rule holds: only word-against-word needs a separator.
Two truths and a lie
Four claims. Three are false.
Eliminate the wrong options
Eliminate the false claims and keep the true one.
Survives elimination: C
Why: Java requires whitespace only where it is needed to separate two words, so it can tell where one ends and the next begins. Everything else — newlines, indentation, extra spaces around punctuation — is for human readers, which is a reason to take it seriously rather than a reason to ignore it.
Concept
If the compiler does not care, why does anyone? Because the compiler is not the only reader — and organisations that do a lot of software development usually have strict guidelines on how to format source code.
Figure (svg): A rule card stating that indentation is for people, not for the compiler, with Google's Java style guide named as an example
You probably will not understand a professional style guide yet — it refers to language features you have not seen. It is worth looking at again every few chapters.
Error analysis
Here the formatting is legal and the program compiles. The indentation is also actively lying to you, which is why this class of bug is so hard to see.
Annotate
Python programmers get this for free, because indentation IS the structure there. In Java it is a promise you make to your future self, and it is only worth anything if you keep it.
Definition probe
Apply the word-against-word test to each marked space.
Sort into buckets
Sort each space by whether Java needs it.
public class; the space in static voidmain (String[] args); the newline after an opening brace; the four spaces indenting a statementCounterexample
You have just seen one. Now say what follows from that.
Discussion prompt
The one-line version of Goodbye compiles and runs correctly. If correctness is what matters, what argument is left for formatting it nicely? Try to make the case without appealing to taste.
Hint: Think about the second time someone reads the program — including you, in a month.
Answer:
The argument is about cost over time. A program is written once and read many times, and every reading of the crushed version costs more attention than a reading of the formatted one.
The sharper version of the argument is about debugging, which is where Section 1.9 is heading: when something goes wrong, you find it by reading. Formatting is not decoration — it is the thing that makes the next bug cheaper to find. That is why companies write it into style guides rather than leaving it to preference.
Ranking
All four compile to the same byte code. Order them best first.
Put in order
Why: Indentation plus one statement per line makes both the structure and the statement boundaries visible. Dropping the indentation loses the structure but keeps the boundaries; crowding statements onto shared lines loses the boundaries too; one long line loses everything. Note that the compiler is completely indifferent to this ordering — it is entirely about the human reader.
Section
Section 1.7
Concept
It is possible to display multiple lines of output with only one line of code. You just have to tell Java where to put the line breaks — and you do that with an escape sequence: two characters of source code that represent a single character.
public class Hello3 {
public static void main(String[] args) {
System.out.print("Hello!\nHow are you doing?\n");
}
}| in the source | characters typed | character produced |
|---|---|---|
| Hello! | 6 | 6 ordinary characters |
| \n | 2 (backslash, n) | 1 newline |
| How are you doing? | 18 | 18 ordinary characters |
| \n | 2 | 1 newline |
The output is two lines, each ending with a newline character. Note that there is no space between the escape sequence and the word after it — if you add one, there will be a space at the beginning of the second line.
Notation
Java has eight escape sequences in total. Think Java lists four, deliberately: these are the ones you will actually reach for, and the backslash is what they all have in common.
Annotate
The book omits the other four on purpose. Its stated goal is teaching you to think like a computer scientist rather than to memorise Java, and Oracle's tutorials are there when you need the rest.
Worked example
This is the escape sequence that most obviously has to exist. Work out why a bare quote cannot possibly work.
System.out.println("She said \"Hello!\" to me.");| character in source | read as | appears in output? |
|---|---|---|
| the first " | start of the string | no |
| She said | data | yes |
| \" | one quotation mark, as data | yes — as " |
| Hello! | data | yes |
| \" | one quotation mark, as data | yes — as " |
| the last " | end of the string | no |
Ask what would happen without the backslashes.
Why: Java would read "She said " as a complete string, then find Hello! sitting outside any string — and refuse to compile.
Add a backslash before each inner quote.
Why: The backslash says: the next character is data, not punctuation. The string no longer ends there.
Count the quotes in the source: there are six.
Why: Two delimit the string; four are escaped and become two visible quotation marks.
Verify: Run it and expect exactly: She said "Hello!" to me.
Why: If the program refused to compile with a message about an unclosed string literal, a backslash is missing — which is precisely the error the escape sequence exists to prevent.
Prediction
One print call, two escape sequences.
System.out.print("one\ntwo\nthree");| piece | effect |
|---|---|
| one | text on line 1 |
| \n | end line 1 |
| two | text on line 2 |
| \n | end line 2 |
| three | text on line 3 — no newline after it |
Predict first
How many lines of output does this single statement produce?
Correct: Three
Why: Two newline characters split the text into three pieces, so three lines appear. Note that the third line is not terminated — print adds nothing, and there is no trailing escape sequence — so whatever is printed next will continue on that same line.
Concept
Once you know about \n, two ways of ending a line become available. They produce identical output, and knowing they are the same thing is worth more than choosing between them.
| written this way | characters sent | output |
|---|---|---|
| println("Hello!") | Hello! plus a newline that println adds | Hello! and the line ends |
| print("Hello!\n") | Hello! plus a newline you wrote | Hello! and the line ends |
| print("a\nb\n") | a, newline, b, newline | two lines, from one statement |
| println("a"); println("b"); | the same four characters | two lines, from two statements |
The last two rows are the same output produced two ways. Escape sequences let one statement produce many lines — which is the point Section 1.7 opens with.
Trap
The mistake. Adding a space after \n for readability, exactly as you would between words in prose.
System.out.print("Hello!\n How are you doing?\n");| character | read as | effect on output |
|---|---|---|
| \n | newline | the line ends |
| (a space) | data | printed at the START of the next line |
| How are you doing? | data | appears, but indented by one space |
The output is Hello! then How are you doing? — with a leading space nobody asked for. It looks like a mysterious indent, and the cause is invisible unless you know to look for it.
The fix. No space between the escape sequence and the text that follows it.
public class Hello3 {
public static void main(String[] args) {
System.out.print("Hello!\nHow are you doing?\n");
}
}| character | read as | effect on output |
|---|---|---|
| \n | newline | the line ends |
| How are you doing? | data | starts at column 1 of the new line |
Think Java flags this explicitly: notice there is no space between \n and How. Inside a string, every character you type is data — including the ones you added to make the source look nicer.
Estimation
Count what Java stores, not what you typed.
String s = "a\tb";| source characters | stored characters |
|---|---|
| a | a |
| \t | one tab |
| b | b |
Predict first
How many characters does the string "a\tb" contain?
Correct: 3
Why: An escape sequence is two characters of source code that represent a single character, so the tab counts once. The string holds a, tab, b — three characters. This matters as soon as you start indexing into strings in Chapter 6, where the positions would be off by one if you counted the backslash.
Matching
Four sequences, four results.
Match the pairs
Why: The last two are the interesting pair. Once the backslash is given a special job, you need an escape for the backslash itself — and for the quote, whose ordinary meaning is 'the string ends here'. Both exist to let you say 'treat this next character as data'.
Edge cases
Push on the escaping rule until it doubles back on itself.
Discussion prompt
You want the output to show the two characters \n — a backslash followed by the letter n — rather than starting a new line. What do you type inside the quotes, and how many characters is that in the source?
Hint: You need to escape the backslash, and then the n is just an ordinary letter.
Answer:
You type \\n — three characters of source: backslash, backslash, n. The first two are an escape sequence producing one backslash; the n that follows is an ordinary letter.
So three source characters produce two output characters. This is the moment escaping starts to feel strange, and it is worth sitting with, because the same idea appears everywhere — in regular expressions, in shell commands, in JSON. The general shape is always: one character is promoted to mean 'the next one is special', so that character needs a way to escape itself.
Section
Sections 1.8-1.9
Concept
One of the most interesting aspects of writing programs is deciding how to solve a problem, especially when there are several solutions. There are numerous ways to sort a list of numbers, and each has its advantages — so we need techniques for describing and analysing solutions formally.
Figure (svg): Three boxes defining algorithm, computer science and debugging, with their one-line definitions underneath
algorithm — A sequence of steps that specifies how to solve a problem. Some algorithms are faster than others; some use less memory.
computer science — The science of algorithms, including their discovery and analysis.
bug — A programming error. The name is historical.
debugging — The process of tracking down programming errors and correcting them.
The book is explicit about its priorities: it intentionally omits some details of Java — such as the other four escape sequences — because being able to understand computation is much more valuable than just learning how to write code.
Picture it
Debugging is like an experimental science. Once you have an idea about what is going wrong, you modify your program and try again — and the outcome tells you which way to go.
Figure (svg): A loop showing observe, hypothesise, predict, test, and then either progress or a new hypothesis
The step people skip is predict. Changing something and seeing what happens is not debugging — it is guessing. Saying what you expect first is what turns a change into an experiment.
Worked example
Section 1.9 gives unusual advice: when you meet a new feature, you should try to make mistakes. Work through it once, deliberately, on Hello World.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!);
}
}| experiment | hypothesis | what javac says |
|---|---|---|
| remove one quotation mark | the string never ends | unclosed string literal, on this line |
| remove both quotation marks | Hello and World become code | several errors — Java tries to read the words as identifiers |
| misspell println as printn | no such method | cannot find symbol: method printn |
| remove the semicolon | the statement never ends | ';' expected — often reported on the NEXT line |
Make one change at a time, on a program you know works.
Why: If you change two things, you cannot attribute the message to either.
Predict the message before compiling.
Why: This is the step that turns the exercise into learning rather than typing.
Read the message, and note where it points.
Why: Some errors are reported one line after the real cause, because that is where the compiler noticed.
Undo the change and confirm the program works again.
Why: Now you know both the error and its cure, and you have a working program to return to.
Verify: You should end with the original program compiling cleanly, and four error messages you can now recognise on sight.
Why: Think Java's reason for all this: it is better to make mistakes now and on purpose than later on and accidentally.
Hypothesis
You hypothesised that a missing semicolon caused the error. You added it. The same error appears.
Predict first
What has that outcome actually told you, and what is the right next move?
Correct: The hypothesis was wrong; form a new one using what the failure ruled out
Why: A refuted prediction is information: the missing semicolon is eliminated as the cause, so the search space is smaller than it was. Think Java puts it plainly — if your hypothesis was wrong, you have to come up with a new one. That is not a setback; it is how the loop makes progress.
Concept
Programming and debugging should go hand in hand. Do not write a large amount of code and then debug by trial and error until it works. Start with a program that does something, and make small modifications, debugging them as you go.
Figure (svg): A rule card contrasting writing everything then debugging against growing a program in small verified steps
That last item is Larry Greenfield's account in The Linux Users' Guide, and Think Java quotes it for a reason: millions of lines of code, grown from a program no more complex than the ones in this chapter.
Error analysis
A student's account of fixing a bug. Every sentence is something people really do, and the whole approach is the one Section 1.9 warns against.
Annotate
Debugging is like detective work: you are confronted with clues, and you have to infer the events that led to the results you see. A detective who changes five things at the scene has destroyed the evidence.
Definition probe
Four of Chapter 1's terms, and situations that illustrate them.
Sort into buckets
Sort each description under the term it defines.
Real world
The book says 'for historical reasons' and moves on. It is worth thirty seconds.
Discussion prompt
Programming errors are called bugs and fixing them is called debugging. Before looking it up: why do you think an error in a piece of text came to be named after an insect?
Hint: The word predates software. Think about what early computers were physically made of.
Answer:
The term predates electronic computers — engineers used bug for a mechanical fault well before software existed. The famous 1947 anecdote is an actual moth found in a relay of the Harvard Mark II, taped into the logbook as 'first actual case of bug being found'.
The joke in that logbook entry only works because the word was already in use for faults. The vocabulary is a small reminder that programming inherited its habits from engineering, which is one of the three fields Chapter 1 opens by naming.
Constraint
The compiler's messages have been helping you. Take them away and see what technique is left.
Discussion prompt
Your program compiles cleanly and runs, but prints Goodbye,cruel world instead of Goodbye, cruel world. There is no error message of any kind. Describe how you would find the cause, in terms of the hypothesis loop.
Hint: What is the smallest difference between what you got and what you wanted?
Answer:
Observe precisely: exactly one character is missing, a space, between the comma and the c. Hypothesise: a string is missing a trailing space. Predict: if I add a space inside the quotes of the first string, the output will be correct. Test: add it and run.
The move that does the work is the first one — describing the symptom precisely enough that the hypothesis becomes obvious. 'It looks wrong' supports no prediction; 'exactly one space is missing between these two characters' nearly names the fix.
This is the kind of error Section 1.8 is preparing you for: no message, no crash, just a wrong answer. Appendix D calls it a logic error, and it is the category the whole book keeps returning to.
Comparison
This lesson gave you several ways to control where output breaks. Fill the blanks to separate them.
Comparison matrix
| written | how many statements | newline comes from | lines produced |
|---|---|---|---|
| println("a"); println("b"); | two | println, twice | two |
| print("a\nb\n"); | one | the escape sequences you wrote | two |
| print("a"); print("b"); | two | nowhere | one (unfinished) |
| println("a\nb"); | one | one escape, plus println's own | two |
The row worth remembering is the third: with no newline anywhere, the line is never finished, and the next thing printed continues it.
Pattern
Everything in this lesson reduces to one distinction, applied in four places: is this character code, or is it data?
| the character | as code | as data |
|---|---|---|
| // | starts a comment | prints, if inside quotes |
| a space | separates two words (required) | part of the string (printed) |
| " | ends the string | prints, if written \" |
| \ | starts an escape sequence | prints, if written \\ |
Check
Work it out before you click.
System.out.print("x");
System.out.print("y");
System.out.println("z");
System.out.println("w");| call | ends the line? |
|---|---|
| print("x") | no |
| print("y") | no |
| println("z") | yes |
| println("w") | yes |
Check your understanding
What exactly does this fragment display?
Answer: A
Why: The two print calls put x and y on the current line without ending it, so z joins them and println then ends that line. The final println puts w on its own line and ends that one too — giving two lines, xyz and w.
Check
Work it out before you click.
Check your understanding
Which statement displays exactly: He said "stop" loudly
Answer: A
Why: Each inner quotation mark must be escaped with a backslash so Java reads it as data rather than as the end of the string. The escape sequence produces one quotation mark in the output, and the backslashes themselves never appear.
stop outside any string — this will not compile.Check
Work it out before you click.
publicclass Test {
public static void main(String[] args) {
System.out.println("hi");
}
}| token | how Java reads it |
|---|---|
| publicclass | one word — an identifier Java does not recognise |
| Test | another word, with no keyword before it |
| the rest | fine on its own |
Check your understanding
Why does this program fail to compile?
Answer: A
Why: Java needs at least one space between two words so it can tell where one ends and the next begins. publicclass is read as a single identifier, and there is no such keyword, so the class definition never starts. Most other spaces are optional, but this one is not.
Real world
The backslash trick you learned for Java strings is not a Java idea. It is one of the most widely reused conventions in computing.
Discussion prompt
You have seen that a character with a special job needs a way to escape itself. Where else have you met a character that had to be written twice, or preceded by something, to mean itself?
Hint: Think about search boxes, file paths, or anywhere you have typed a quotation mark inside a quotation mark.
Answer:
The same shape appears in JSON (identical backslash escapes), regular expressions (where a literal dot must be written as an escaped one), shell commands (quoting a filename with a space in it), CSV files (a doubled quotation mark inside a quoted field), and URLs (a space becomes %20).
Once you can recognise the pattern — some character was promoted to punctuation, so it needs an escape to be data again — a whole class of confusing errors becomes predictable. The question to ask when text arrives mangled is always: which character did this system treat as punctuation?
Commit first
Commit to an answer and to your confidence.
Predict first
How many characters does Java store for the string "a\\b"?
Correct: 3
Why: The source shows a, backslash, backslash, b — four characters typed. But \\ is an escape sequence: two source characters representing one real backslash. So the stored string is a, backslash, b — three characters. Counting stored characters rather than typed ones is the habit that keeps string indexing correct in Chapter 6.
Explain it
The test of understanding an escape sequence is being able to say why it has to exist.
Discussion prompt
Explain to someone who has just written their first program why you cannot simply put a quotation mark inside a string, and what the backslash does about it. You may not use the word 'escape' in your explanation.
Hint: Start from the compiler's problem, not from the solution.
Answer:
A version that works: the quotation mark is how Java knows where the text stops. So if you put one in the middle of your text, Java stops there — it has no way to tell that you meant it as a letter rather than as the end. The backslash is how you tell it: it says 'the next character is part of my text, not a signal'.
If your explanation started with 'you write backslash-quote', it described the rule without explaining the problem — which is the version people forget. The problem is that one character is doing two jobs, and the backslash is how you say which job you mean.
Exit ticket
One question before you close the deck.
Predict first
What does print("Hello\n") do that println("Hello") does not?
Correct: Nothing — the two produce identical output
Why: println appends a newline for you; \n is that same newline written by hand. Both send the text Hello followed by one newline character, so the output is identical. Seeing these as the same thing — rather than as two unrelated features — is what makes the choice between print and println a deliberate one about where lines should end.
Connect it up
One page, from memory.
Draw it
Draw a line of output as a row of boxes, one character per box, for the program that prints Goodbye, cruel world. Mark which boxes came from which statement, and circle the space that a beginner usually leaves out. Then, underneath, write the four escape sequences and what each produces. Finally, in one sentence, write the rule that connects comments, spaces, quotes and backslashes.
Recap
Five sections, one idea running through all of them: the compiler is always deciding whether it is reading code or reading data, and most of this lesson's rules are about telling it which.
| if you remember one thing | it is this |
|---|---|
| about output | println ends a line, print continues one |
| about strings | inside quotes, every character is data |
| about debugging | one change, one prediction, one run |
// is just text.Want this taught 1-on-1? Alexander tutors Java — $55/session, free consultation.