Printing, Escape Sequences, and Debugging

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

What this lesson covers

The lesson, slide by slide

1. Printing, Escape Sequences, and Debugging

Title

Think Java 2e · Chapter 1 · Computer Programming

Sections 1.5-1.9 · pp. 6-12

2. What you will be able to do

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.

3. Retrieve before you read

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.

4. One program, four small changes

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.

5. As many statements as you like

Section

Section 1.5

6. main can hold more than one statement

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
    }
}
orderstatementwhat appears
1println("Hello, World!")Hello, World!
2println("How are you?")How are you?
—the two // commentsnothing — 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.

7. Statements run in source order

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.

8. Predicting output before running

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");
    }
}
lineruns?output line
println("one")yesone
// println("two")no — commented out(none)
println("three")yesthree

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.

9. How many lines of output?

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");
statementlive?
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?

  • 2
  • 1
  • 3
  • 4

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.

10. Two places a comment can go

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.

styleexamplewhen to use it
on its own line// generate some simple outputexplaining the block of code that follows
at the end of a lineSystem.out.println("Hi"); // first linea 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.

11. A comment inside a string is not a comment

Trap

The trap

The assumption. // always means 'ignore the rest of the line'.

System.out.println("Visit http://example.com");
expected by the assumptionwhat actually happens
Java ignores from the first // onwardthe // is inside quotes, so it is ordinary text
output: Visit http:output: Visit http://example.com
the statement is brokenthe 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 fix

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 questioncode or data?effect
inside the quotesdataprinted as part of the text
after the semicoloncodestarts 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.

12. Why does order matter so much here?

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.

13. Add a third message

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.

14. What does 'top to bottom' actually guarantee?

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.

15. print, println, and the newline

Section

Section 1.5, continued

16. println appends a newline; print does not

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");
    }
}
statementtext sentnewline added?cursor ends
print("Goodbye, ")Goodbye, nojust after the space
println("cruel world")cruel worldyesstart 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.

17. Where the cursor is after each call

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.

18. Building one line from three calls

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");
    }
}
statementoutput 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.

19. How many lines does this produce?

Prediction

Two prints and one println.

System.out.print("a");
System.out.print("b");
System.out.println("c");
callnewline appended?
print("a")no
print("b")no
println("c")yes

Predict first

How many lines of output, and what do they contain?

  • One line: abc
  • Three lines: a, b, c
  • Two lines: ab then c
  • One line: a b c

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.

20. Strings, and what is in them

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.

21. Four printlns are not one line

Trap

The 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");
statementnewline?result
println("2")yesline 1: 2
println(" + ")yesline 2: +
println("2")yesline 3: 2
println(" = 4")yesline 4: = 4

Four lines instead of one, and the leading spaces now look like stray indentation.

The fix

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");
statementnewline?result
print("2")no2
print(" + ")no2 +
print("2")no2 + 2
println(" = 4")yes2 + 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.

22. print or println?

Discrimination

For each goal, decide which method the last call should use.

Sort into buckets

Sort each situation by the method it calls for.

print
the "Goodbye, " half of a single line; a label that a value will be printed after, on the same line
println
the final line of your program's output; each row of a multi-line report
pr
Use print when something else will be added to the same line afterwards — a label before a value, or one piece of an assembled line.
pl
Use println when this call should finish the line, so the next output starts fresh below it.

23. Where did the space go?

Error analysis

A student expects Goodbye, cruel world and gets Goodbye,cruel world. The annotations locate the missing character.

Annotate

  • The first string ends at the comma. There is no trailing space inside the quotes, so nothing separates it from what follows.
  • Java adds nothing between calls. print sends exactly the characters between the quotes — no separator, no space, ever.
  • The fix is one character, inside the quotes: "Goodbye, ". Putting the space outside the quotes, in the source, does nothing at all — that space is formatting for you, not data.
  • This is the first appearance of a rule worth generalising: whitespace inside quotes is data; whitespace outside quotes is layout. The next section is entirely about the second kind.

Bugs of exactly one character are the common case, not the exception. Learning to look for them is the point of Section 1.9.

24. Recover the calls from the output

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.

25. Which spaces Java requires

Section

Section 1.6

26. Some spaces are required; most are not

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 removedlegal?why
the spaces between public, class and GoodbyenopublicclassGoodbye is a single word to Java, and it means nothing
the spaces inside String[] argskeptthe example leaves these in — they are between words too
the newlineswould be legalnewlines 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.

27. The same program, three ways

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.

28. Deciding whether a space is required

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 spacebetweenrequired?
public_statictwo wordsyes
static_voidtwo wordsyes
void_maintwo wordsyes
main_(a word and a punctuation markno
String[]_argstwo wordsyes
)_{two punctuation marksno

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.

29. Which claim about whitespace survives?

Two truths and a lie

Four claims. Three are false.

Eliminate the wrong options

Eliminate the false claims and keep the true one.

  • A. All spaces in a Java program are optional.
  • B. Indentation determines which statements are inside a method.
  • C. Spaces between two words are required; most others are optional.
  • D. Removing all newlines makes a program illegal.

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.

30. Why formatting is worth caring about anyway

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.

31. Formatting that hides a real bug

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

  • All three statements are siblings. They are all directly inside main's braces, and all three run, in order.
  • The indentation suggests otherwise. The second line looks nested inside the first, and the third looks as though it escaped the method entirely.
  • Java does not care — indentation is whitespace, and whitespace outside quotes is optional. The braces alone decide what contains what.
  • But you will care, the moment there is an actual nested block in Chapter 5. If you have trained yourself to read indentation as structure, misleading indentation will send you looking for a bug in the wrong place.
  • The habit to build now: indent to match the braces, always — so that when the two disagree, you notice.

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.

32. Required or optional?

Definition probe

Apply the word-against-word test to each marked space.

Sort into buckets

Sort each space by whether Java needs it.

required
the space in public class; the space in static void
optional
the space in main (String[] args); the newline after an opening brace; the four spaces indenting a statement
req
Two words sit either side, so without a space Java reads them as one word it does not recognise.
opt
Punctuation or a line ending already marks the boundary, so the whitespace is for human readers only — which does not make it worthless.

33. Can a legal program be unreadable?

Counterexample

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.

34. Order these by readability

Ranking

All four compile to the same byte code. Order them best first.

Put in order

  1. One statement per line, indented to match the braces
  2. One statement per line, no indentation at all
  3. Several statements per line, some line breaks
  4. The entire program on a single line

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.

35. Escape sequences

Section

Section 1.7

36. Two characters that mean one

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 sourcecharacters typedcharacter produced
Hello!66 ordinary characters
\n2 (backslash, n)1 newline
How are you doing?1818 ordinary characters
\n21 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.

37. The four escape sequences worth knowing

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

  • \n — newline. Moves to the beginning of the next line. This is the same character println appends for you, which means println("x") and print("x\n") do the same thing.
  • \t — tab. Moves to the next tab stop. Useful for lining up columns of output before you learn proper formatting in Chapter 3.
  • \" — double quote. The one that needs explaining: a bare " would end the string, so the backslash tells Java this quote is data rather than a boundary.
  • \\ — backslash. Because the backslash now has a special job, you need a way to say "an actual backslash". Two of them mean one.
  • Notice the pattern: the backslash is an escape from the string's normal rules. Think Java's phrasing is exact — it lets you 'escape the string to write special characters'.

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.

38. Putting quotation marks inside a string

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 sourceread asappears in output?
the first "start of the stringno
She said datayes
\"one quotation mark, as datayes — as "
Hello!datayes
\"one quotation mark, as datayes — as "
the last "end of the stringno

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.

39. How many lines does one statement produce?

Prediction

One print call, two escape sequences.

System.out.print("one\ntwo\nthree");
pieceeffect
onetext on line 1
\nend line 1
twotext on line 2
\nend line 2
threetext on line 3 — no newline after it

Predict first

How many lines of output does this single statement produce?

  • Three
  • One
  • Two
  • Four

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.

40. println versus print with an escape

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 waycharacters sentoutput
println("Hello!")Hello! plus a newline that println addsHello! and the line ends
print("Hello!\n")Hello! plus a newline you wroteHello! and the line ends
print("a\nb\n")a, newline, b, newlinetwo lines, from one statement
println("a"); println("b");the same four characterstwo 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.

41. A stray space after the escape sequence

Trap

The 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");
characterread aseffect on output
\nnewlinethe line ends
(a space)dataprinted at the START of the next line
How are you doing?dataappears, 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

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");
    }
}
characterread aseffect on output
\nnewlinethe line ends
How are you doing?datastarts 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.

42. How many characters is that string?

Estimation

Count what Java stores, not what you typed.

String s = "a\tb";
source charactersstored characters
aa
\tone tab
bb

Predict first

How many characters does the string "a\tb" contain?

  • 3
  • 4
  • 2
  • 5

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.

43. Match each escape sequence to what it produces

Matching

Four sequences, four results.

Match the pairs

  • n. \n
  • t. \t
  • q. \"
  • b. \\
  • r1. moves to the beginning of the next line
  • r2. moves to the next tab stop
  • r3. a double quote, as data rather than a string boundary
  • r4. a single backslash character

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'.

44. What would print a literal backslash-n?

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.

45. Algorithms, bugs, and debugging

Section

Sections 1.8-1.9

46. An algorithm is a sequence of steps

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.

47. Debugging as a hypothesis loop

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.

48. Debugging a program on purpose

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!);
    }
}
experimenthypothesiswhat javac says
remove one quotation markthe string never endsunclosed string literal, on this line
remove both quotation marksHello and World become codeseveral errors — Java tries to read the words as identifiers
misspell println as printnno such methodcannot find symbol: method printn
remove the semicolonthe 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.

49. Your prediction was wrong. Now what?

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?

  • The hypothesis was wrong; form a new one using what the failure ruled out
  • Nothing useful; change something else at random and try again
  • The compiler is mistaken; ignore the message
  • Add several more semicolons in case one is still missing

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.

50. Grow a program; do not write it all at once

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.

51. Trial-and-error is not debugging

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

  • 'I wrote all 60 lines, then it didn't work.' The failure could be in any of the 60. Growing the program in steps would have narrowed it to the newest few.
  • 'I changed the loop AND the print statement.' Two changes at once: if the behaviour changes, neither one is confirmed as the cause.
  • 'Still broken' — with no prediction recorded, this outcome teaches nothing. There was no hypothesis for it to refute.
  • 'I don't know which one fixed it.' This is the real cost. The program works and the student has learned nothing, so the same bug will cost the same amount of time next week.
  • The alternative is one change, one prediction, one run. It feels slower and it is dramatically faster, because every run either confirms or eliminates something.

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.

52. Sort these into the book's vocabulary

Definition probe

Four of Chapter 1's terms, and situations that illustrate them.

Sort into buckets

Sort each description under the term it defines.

algorithm
a sequence of steps that specifies how to solve a problem
a bug
the program compiles but prints the wrong answer
debugging
changing the program, running it, and comparing against a prediction
computer science
the science of discovering and analysing solutions like these
alg
An algorithm is the method itself — the steps, independent of any language you write them in.
bug
A programming error. Note that this one compiles perfectly: legal is not the same as correct.
dbg
The process of tracking errors down and correcting them, which the book frames as experimental science.
cs
The science of algorithms, including their discovery and analysis — which is why several algorithms for one problem is interesting rather than wasteful.

53. Why is it called a bug?

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.

54. Debug with no error message at all

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.

55. Four ways to end a line, compared

Comparison

This lesson gave you several ways to control where output breaks. Fill the blanks to separate them.

Comparison matrix

writtenhow many statementsnewline comes fromlines produced
println("a"); println("b");twoprintln, twicetwo
print("a\nb\n");onethe escape sequences you wrotetwo
print("a"); print("b");twonowhereone (unfinished)
println("a\nb");oneone escape, plus println's owntwo

The row worth remembering is the third: with no newline anywhere, the line is never finished, and the next thing printed continues it.

56. The pattern to carry away

Pattern

Everything in this lesson reduces to one distinction, applied in four places: is this character code, or is it data?

the characteras codeas data
//starts a commentprints, if inside quotes
a spaceseparates two words (required)part of the string (printed)
"ends the stringprints, if written \"
\starts an escape sequenceprints, if written \\

57. Check: print and println

Check

Work it out before you click.

System.out.print("x");
System.out.print("y");
System.out.println("z");
System.out.println("w");
callends the line?
print("x")no
print("y")no
println("z")yes
println("w")yes

Check your understanding

What exactly does this fragment display?

  • A. xyz on one line, then w on the next (correct)
  • B. x, y, z, w on four separate lines
  • C. xyzw on one line
  • D. xy on one line, then z, then w

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.

Why B tempts people
This treats every call as though it ended a line, but print does not append a newline — only println does.
Why C tempts people
This ignores the newline that the first println appends, which is what separates w onto a second line.
Why D tempts people
This has z starting a new line, but println writes its text on the CURRENT line and only then moves down.

58. Check: escape sequences

Check

Work it out before you click.

Check your understanding

Which statement displays exactly: He said "stop" loudly

  • A. System.out.println("He said \"stop\" loudly"); (correct)
  • B. System.out.println("He said "stop" loudly");
  • C. System.out.println("He said \\stop\\ loudly");
  • D. System.out.println("He said \n stop \n 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.

Why B tempts people
The unescaped quote after 'said ' ends the string, leaving stop outside any string — this will not compile.
Why C tempts people
\\ is the escape for a single backslash, so this would display backslashes rather than quotation marks.
Why D tempts people
\n is a newline, so this would break the text across three lines instead of quoting the word.

59. Check: what the compiler requires

Check

Work it out before you click.

publicclass Test {
    public static void main(String[] args) {
        System.out.println("hi");
    }
}
tokenhow Java reads it
publicclassone word — an identifier Java does not recognise
Testanother word, with no keyword before it
the restfine on its own

Check your understanding

Why does this program fail to compile?

  • A. A required space between two words is missing (correct)
  • B. The indentation is inconsistent
  • C. The class name does not match the file name
  • D. println should be print

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.

Why B tempts people
Indentation is whitespace outside quotes and has no effect on the compiler at all — it is for human readers.
Why C tempts people
Nothing here tells you the file name, and in any case that error would name the required file explicitly.
Why D tempts people
Both print and println are real methods; choosing between them affects the output's line breaks, not whether it compiles.

60. Escaping, everywhere you look

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?

61. How sure are you?

Commit first

Commit to an answer and to your confidence.

Predict first

How many characters does Java store for the string "a\\b"?

  • 3
  • 4
  • 2
  • 5

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.

62. Explain it to someone else

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.

63. Exit ticket

Exit ticket

One question before you close the deck.

Predict first

What does print("Hello\n") do that println("Hello") does not?

  • Nothing — the two produce identical output
  • It prints the characters backslash and n
  • It leaves the cursor on the same line
  • It prints two lines instead of one

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.

64. Draw the whole lesson

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.

65. Recap

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 thingit is this
about outputprintln ends a line, print continues one
about stringsinside quotes, every character is data
about debuggingone change, one prediction, one run

Sources

  1. 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
  2. The Java Tutorials — Characters (escape sequences)
  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