Volume 1 Companion: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Companion: Foundations of Computing

V1·01

Start Here: Computers, Programs and Your Toolbox

Companion to Volume 1, chapter 01: a concept map of how the machine, bits, programs, the terminal and errors connect; eleven other ways to see the chapter (code-first, CPU time stretched to human time, bits as yes/no questions, the clerk who can't read, exit codes as a one-byte telegram, Python's hidden compiler); what it oversimplifies and the theory behind it (five averaging programs that disagree, a C compiler that accepts a string as an int, the halting problem, leaky abstractions); real launcher code from CPython and the JDK; four debugging drills; interview questions with how to approach each.

6 sections · ~26 min to read
Updated Suggest a correction

Understanding it better

Concept map

The chapter has five strands, and every later chapter pulls on at least one of them. Read the map left to right: the machine runs programs, everything either touches is bits given a meaning, and you drive all of it from the terminal, where errors come back to you.

the machine information programs computerinput → process → store → output CPU: runs instructions RAM: fast, volatile storage: big, persistent operating system bits and bytes8 bits = 256 patterns meaning = interpretation text · images · sound· instructions algorithmsteps, incl. unusual cases source code compiler · interpreter· JVM (bytecode + JIT) machine code terminal + shell paths · stdin/out/err· arguments · exit codes errors: compile · run· logic (only tests) loaded into machine code runs on the CPU are bits starts what the shell asks for paths name files in storage reports compile errors a non-zero exit code reports a failure goes deeper: ch2 types and testing · ch4 algorithms · ch6 bits and numbers · ch7 hardware · ch8 operating systems and processes · ch10 compilers and interpreters
Concept map of chapter 01. Three columns: the machine (computer as input-process-store-output, CPU, RAM, storage, operating system), information (bits and bytes, interpretation as type, text, images, sound and instructions) and programs (algorithm, source code, compiler or interpreter or JVM, machine code). Machine code is bits and runs on the CPU; storage is loaded into RAM. A bottom row shows the terminal and shell, paths and streams and exit codes, and the three kinds of error. Paths name files in storage, the operating system runs the programs the shell starts, and the translator reports compile errors. Labels name the later chapters that go deeper.

Three links in the map are the ones beginners miss, and they come back in every volume:

  • Instructions are bits too. A program sits in storage as bytes, gets loaded into RAM, and the CPU executes it. That's why one machine can be a word processor or a web server, and why the same .exe won't run on a different processor type (exercise T14).
  • Meaning is an agreement, not a property of the bits. 72 105 is "Hi", or the number 18,537, or a Chinese character, depending on who reads it (see Explain it differently below). Types (chapter 2) and encodings (chapter 6) are that agreement written down.
  • The terminal is where the strands meet. A command names a file by its path, the shell asks the OS to start a program with arguments, the program reads stdin and writes stdout and stderr, and its exit code tells the next command whether to go on.

Explain it differently

The chapter teaches theory first, with a kitchen. Here's the same material code-first: run each command, predict before you look, and let the machine show you the ideas. Every output below is real (Ubuntu 24.04, bash).

1. Everything is bytes, and meaning is chosen by the reader. Write two characters into a file and look at the raw bytes:

Terminal
$ printf 'Hi' > hi.bin
$ ls -l hi.bin | awk '{print $5, $NF}'
2 hi.bin
$ od -An -tu1 hi.bin
  72 105
$ python3 -c 'b=open("hi.bin","rb").read(); print(b, list(b), int.from_bytes(b,"big"), b.decode("utf-16-be"))'
b'Hi' [72, 105] 18537 䡩

The file is 2 bytes. Read as ASCII text, it's Hi. Read as one 16-bit big-endian number, it's 72 × 256 + 105 = 18,537. Read as UTF-16 text, it's the character 䡩. Nothing in the file says which reading is right. That's the chapter's sentence "the same bits mean different things depending on how they're interpreted", demonstrated.

And not every character is one byte:

Terminal
$ printf '₹' | od -An -tu1
 226 130 185

The rupee sign takes three bytes in UTF-8. The chapter's "one letter of English text" per byte is true for English only. Chapter Exercises, "Text is Unicode, not just ASCII", covers why.

2. A program is a process with three channels and a result. Instead of reading about stdout, stderr and exit codes, watch them separate:

Terminal
$ ls /nope
ls: cannot access '/nope': No such file or directory
$ echo "exit=$?"
exit=2
$ ls /nope 2>/dev/null | wc -l
0
$ echo "pipeline exit=$?"
pipeline exit=0

Three lessons in four commands:

  • The error message went to stderr: discarding stderr with 2>/dev/null left wc counting 0 lines of real output.
  • ls reported failure with exit code 2.
  • A pipeline's exit code is the last command's: wc succeeded, so the pipeline says 0 even though ls failed. Drill D3 below shows how this hides failed builds.

3. Compiling versus interpreting, by timing when a mistake is noticed. The chapter lists compiler, interpreter and JVM. The quickest way to feel the difference is to put the same mistake in each and see when it's caught. The chapter shows Python catching a misspelt name only when line 5 runs, and Go rejecting "three" before anything runs. Chapter Exercises P10 ("When does each language notice a mistake?") is exactly this experiment across all seven languages, so it isn't repeated here.

4. An analogy for the whole chapter: a train ticket machine. If the kitchen didn't stick, try this one:

  • You press buttons and insert money (input).
  • The machine works out the fare (processing, by the CPU following a program).
  • It remembers your choices while you're at it (RAM) and keeps the fare table between restarts (storage).
  • It prints the ticket (output) and returns your change or a refusal code (exit code).
  • Its program was written by people as source code, translated once and installed (compiler).
  • A fare table update is just new data loaded into the same machine (instructions and data are both bits).
  • When someone types a fare of "abc", a well-written machine refuses politely (input validation), and a badly written one charges ₹12 (drill D1).

5. Time as distance: stretch a CPU cycle to one second. "RAM is fast, storage is slower" doesn't tell you how much slower. Scale everything up so that one CPU cycle (about 0.3 ns at 3.3 GHz) takes one second, and keep the ratios:

Operation Real time (typical) If one CPU cycle took 1 second
one CPU cycle 0.3 ns 1 second
read from RAM 100 ns 5.6 minutes
read from an SSD 100 µs 3.9 days
hard-disk seek 10 ms 1.06 years
network round trip, Hyderabad to the US east coast about 250 ms 26 years

(Computed from the real times in the second column; the times themselves are typical orders of magnitude, not measurements of one machine.)

Now the chapter's rule "programs load data from storage into memory before working on it" becomes obvious: no cook walks to a pantry four days away for every pinch of salt. It also explains much of the rest of this book: caches (chapter 7) exist to avoid the five-minute RAM trip, and nearly every backend performance problem is a 26-year network trip made too many times (Volume 3's N+1 queries).

6. Counting choices: a bit is one yes/no answer. The chapter says 8 bits give 256 patterns. Turn it round: the number of bits you need is the number of yes/no questions it takes to pick one item from all the possibilities, which is log₂ of the number of choices, rounded up.

To pick one of… Choices log₂ (choices) Bits needed
a coin flip 2 1 1
an English letter (one case) 26 4.70 5
a letter, upper or lower case 52 5.70 6
a number from 0 to 255 256 8 8 (one byte)
one of a million 1,000,000 19.93 20
one person in India (about 1.43 billion) 1.43 × 10⁹ 30.41 31

So "how many bits do I need?" is a guessing game: each bit halves the possibilities. Thirty-one well-chosen yes/no questions can find any one person in India. This is the idea behind binary search (chapter 4) and information theory, and it's why a 32-bit ID runs out at about 4.3 billion.

7. The clerk who can't read. Picture a clerk in a windowless room with a wall of numbered boxes (memory), each holding a number from 0 to 255, and a rule card (the program): "add box 12 to box 13, put the result in box 14; if box 14 is more than 100, jump to rule 9". The clerk is fast and never makes a mistake, but can't read: the clerk doesn't know whether box 12 holds part of a photo, a letter or a rupee amount, and never needs to. Every meaning (text, colour, money) exists only in the heads of the people who wrote the rules and who look at the output. That's why mixing up interpretations produces nonsense without any error: the clerk happily adds the code for A to the code for 7. Types (chapter 2) are labels we paint on the boxes so that our tools can stop us doing that, because the clerk never will.

8. Three parties who can object. Every program involves three parties, and the chapter's three kinds of error are simply which party objected:

Party What it checks When it objects, you get…
the translator (compiler, or the interpreter's parser) that the text is well-formed and, in typed languages, that types fit a compile-time error: your text isn't a valid program
the machine (CPU, OS, runtime) that each step is possible right now: the file exists, the index is in range, you're not dividing by zero a run-time error: a valid program asked for something impossible
the author (you, or the person who wrote the requirement) that the result is what was meant a logic error: only a person, or a test written by one, can object

Seen this way, it's clear why logic errors produce no message (the only party who could object wasn't in the room), and why tests matter: a test is the author's objection, written down in advance so the machine can raise it for you.

9. The switchboard: a program never knows who it's talking to. The shell connects a program's three channels before the program starts, like an operator plugging cables into a switchboard. The program just reads from "line 0" and writes to "lines 1 and 2". It can ask whether a line goes to a person's terminal, and some programs behave differently when it doesn't:

Terminal
$ python3 -c 'import sys; print("stdout is a terminal:", sys.stdout.isatty())' | cat
stdout is a terminal: False
$ script -qc "python3 -c 'import sys; print(\"stdout is a terminal:\", sys.stdout.isatty())'" /dev/null
stdout is a terminal: True

(script runs a command inside a pretend terminal.) This is why ls prints in columns and colour on screen but one plain name per line into a pipe, and why a program's output can look different in your terminal and in a log file. Redirection, pipes and files all work because programs talk to lines, not to devices.

10. The exit code is a one-byte telegram. The chapter says a program returns "a number". It's a very small number: the operating system keeps only one byte of it, so values wrap round at 256:

Terminal
$ bash -c 'exit 256'; echo $?
0
$ bash -c 'exit 300'; echo $?
44

A program that "returns the number of errors" as its exit code reports success when it finds exactly 256 errors (300 becomes 300 − 256 = 44). The telegram has room for one byte, so use it for a small agreed vocabulary (0 success, 1 failure, 2 usage error…) and put details on stderr.

11. Python has a compiler you never see. The chapter calls Python interpreted "with a twist". Here's the twist, made visible: ask Python to show the instructions it compiled from a two-line file.

Terminal
$ cat two.py
total = 120 + 80
print(total)
$ python3 -m dis two.py
  0           RESUME                   0

  1           LOAD_CONST               0 (200)
              STORE_NAME               0 (total)

  2           LOAD_NAME                1 (print)
              PUSH_NULL
              LOAD_NAME                0 (total)
              CALL                     1
              POP_TOP
              RETURN_CONST             1 (None)

There's no addition in the output: 120 + 80 became the constant 200 before the program ran (constant folding, a classic compiler optimisation). So CPython really does compile, to bytecode for its own virtual machine, much like javac. The difference from Java is mainly when (just before running, cached in __pycache__) and that CPython doesn't, by default, compile further to machine code. "Compiled" against "interpreted" is a spectrum, not two boxes.

Gaps and misconceptions

What the chapter oversimplifies

1. "Every version prints the same result." That's true for the chapter's input (120, 80, lunch, a blank line, 150.5). On other input the five averaging programs disagree. Each cell below shows what the chapter's own program (copied exactly) did with a single line of input: the value it accepted, or skip.

Input line Python C Java Go Rust
12abc skip 12.00 skip skip skip
nan nan nan skip NaN NaN
inf inf inf skip +Inf inf
1_000 1000.00 1.00 skip 1000.00 skip
1d skip 1.00 1.00 skip skip
0x10 skip 16.00 skip skip skip
7 7.00 7.00 7.00 7.00 7.00
1e400 inf inf Infinity skip inf
٣ (Arabic-Indic 3) 3.00 skip skip skip skip
1,5 skip 1.00 skip skip skip

Fed all ten lines at once, the programs reported counts of 6, 9, 3, 4 and 4. Each language's number parser has its own rules:

  • C's strtod stops at the first character it can't use and keeps what came before (12abc becomes 12; 1,5 becomes 1). It also accepts hex floats.
  • Java's parseDouble accepts a d or f suffix, as in Java source code.
  • Python's float accepts underscores and any Unicode decimal digit.
  • Go rejects 1e400 because it's out of range.

The lesson the chapter leaves implicit: "a number" isn't defined until you define it. Real programs state the accepted format and validate it, rather than accepting whatever the parser accepts. Chapter Exercises P11 hardens the Java version. Drill D1 below fixes the C one.

2. "Go (like C, C++, Java, Rust and Zig) checks types before running, so this mistake can never reach users." C's checks are much weaker than the sentence suggests. GCC 13 (the version the chapter used) accepts the chapter's own example, translated to C:

C
#include <stdio.h>
int main(void) {
    int count = "three";
    printf("%d\n", count);
    return 0;
}
Terminal
$ gcc t.c -o t
t.c: In function 'main':
t.c:3:17: warning: initialization of 'int' from 'char *' makes integer from pointer without a cast [-Wint-conversion]
    3 |     int count = "three";
      |                 ^~~~~~~
$ echo $?
0
$ ./t
-835833852

It's only a warning: the build succeeds (exit 0) and the program prints part of a memory address. GCC 14 turned this warning into an error by default, and -Werror=int-conversion does the same on GCC 13 (the build then fails with exit 2). The accurate version: compiled languages check types before running, to the degree the language defines. C's rules are loose and C compilers keep many checks as warnings, so read warnings, and build with -Wall -Werror in real projects.

3. "Java 11+: compile and run in one step (single files)." True in Java 11, and Java has moved on twice since:

  • JDK 22 can launch multi-file source programs (JEP 458).
  • JDK 25 finalised compact source files and instance main methods (JEP 512): void main() { … } with no class and no static.

On the chapter's JDK 21 that compact form is only a preview, and it fails without a flag:

Terminal
$ cat Simple.java
void main() { System.out.println("no class, no static"); }
$ java Simple.java
Simple.java:1: error: unnamed classes are a preview feature and are disabled by default.
void main() { System.out.println("no class, no static"); }
^
  (use --enable-preview to enable unnamed classes)
1 error
error: compilation failed

So the hello-world boilerplate the chapter explains line by line (public class, static, String[] args) is now optional in current Java. The launcher code that decides how to call main is in the Code walkthrough below.

4. "A kilobyte (KB) is about a thousand bytes." Under SI and IEC rules, a kilobyte is exactly 1,000 bytes and a kibibyte (KiB) is exactly 1,024. "About" makes it sound like loose talk, when it's really two precise units that people mix up. The chapter defers the details to chapter 6; Chapter Exercises T7 ("The missing gigabytes") works through the consequence.

Common misconceptions

Misconception What's actually true Where it's shown
"Python isn't compiled." CPython compiles source to bytecode first (cached as .pyc in __pycache__), then interprets the bytecode. The chapter mentions this "twist" in one clause. chapter, "Programming languages"
"Java is interpreted, so it's slow." The JVM interprets at first, then JIT-compiles hot code to machine code. Long-running Java is often close to C speed. Chapter Exercises P14 measures it
"Exit code 0 means the output is right." 0 means the program reported success. A logic error still exits 0. chapter, "Three kinds of errors"
"A relative path is relative to the script's folder." It's relative to the process's current working directory. Chapter Exercises T15, C2
"The line in the error message is where the bug is." Often it's the line before (C's missing ;), or far away (a bad value created earlier). chapter, "Four real messages"
"> file captures everything the program prints." It captures stdout only. Errors still go to the screen unless you add 2>. chapter, "Check yourself"
"A failing command stops a script." Bash carries on after failures unless told otherwise, and a pipeline reports only its last command's status. drill D3 below
"Memory and storage are the same, just different sizes." RAM is volatile and about 1,000× faster than an SSD. Data is only safe once it's on storage and flushed. The chapter, "The parts, and a kitchen to remember them by"

Theoretical gaps: what the chapter's model of computing leaves out

The chapter gives a working picture: a CPU follows a list of instructions, one after another, and you predict the result by tracing. That picture is right for beginners and wrong in ways that matter later. These are the deeper ideas behind it, with the chapter that develops each.

1. Every general-purpose computer can compute the same things. The chapter says languages differ "because they make different trade-offs". What it doesn't say is that, in what they can compute, they don't differ at all. Any general-purpose language with unbounded memory (C, Python, Java, even a spreadsheet with enough cells) can compute exactly the same set of functions. This is Turing completeness, and the Church–Turing thesis says nothing more powerful has been found. So "you can't do X in Python" is never about possibility. It's about speed, memory control, safety, convenience or available libraries. Choosing a language is choosing trade-offs, never choosing capability. (Volume 1, chapters 5 and 10.)

2. Some questions about programs can't be answered by any program. The chapter's best advice is "predict what a program will do before running it", with a trace table. That works for small programs, but there's a hard limit. No program can decide, for every program and input, whether it will finish (the halting problem, Turing, 1936). The same reasoning (Rice's theorem) shows that no tool can decide any non-trivial behaviour of arbitrary programs, such as "does this ever print a negative number?". That's why:

  • compilers and linters give warnings that are sometimes wrong in both directions;
  • type systems deliberately reject some correct programs, so they can guarantee things about the rest;
  • testing can show the presence of bugs, but never their absence (Dijkstra's line).

The limit is mathematical, not a weakness of today's tools. (Chapter 5, and Volume 11 on testing.)

3. "Instructions run one after another" is an illusion that's carefully maintained. Modern CPUs pipeline instructions, execute them out of order, and guess the result of if branches before they know the answer. Compilers reorder, merge and delete code (item 11 of Explain it differently showed Python deleting an addition). All of this is allowed under one rule: the observable behaviour must be as if the program ran in order. For a single-threaded program you can't tell the difference, which is why the chapter's trace tables still work. With two threads the illusion breaks, and programs need explicit rules about what each thread can see (memory models, Volume 3 chapter 38). (Chapters 7 and 10.)

4. Compiled and interpreted describe implementations, not languages. The chapter's table sorts languages into compiled and interpreted. But it's each implementation that compiles or interprets:

  • Python has an interpreter (CPython, which also compiles to bytecode: see item 11 of Explain it differently) and a JIT compiler (PyPy);
  • Java has a JIT (HotSpot) and ahead-of-time compilation (GraalVM native image);
  • C is normally compiled, but C interpreters exist.

"Is Python slow?" really means "is CPython slow for this workload?". (Chapter 10.)

5. An algorithm has a stricter definition than "a recipe". The chapter's definition is fine for chapter 1. The classical one (Knuth) asks for five things:

  • finiteness: it always stops;
  • definiteness: every step is unambiguous;
  • input and output;
  • effectiveness: each step can actually be carried out.

Many real "recipes" fail it: a server's main loop never stops (so it isn't an algorithm in this sense, but a process), and "pick a good pivot" isn't definite until you say how. This distinction becomes practical in chapter 4, where "does it terminate, and how fast?" is the first question about any algorithm.

6. Abstractions leak. The kitchen model (CPU, worktop, pantry) is an abstraction: it hides details so you can think. Every abstraction in computing leaks sooner or later. The worktop isn't uniformly fast (caches make some memory 100× faster than other memory). The pantry isn't always safe (data written to storage can sit in a RAM buffer first). The cook can be interrupted (the OS switches programs). Senior engineers are distinguished less by knowing more abstractions than by knowing where each one leaks and what it costs when it does. (Joel Spolsky's "law of leaky abstractions"; chapters 7 and 8.)

7. A byte wasn't always 8 bits, and C still allows other sizes. The chapter states "8 bits make a byte". On today's machines that's true, but it's a convention that won around the 1970s: some early computers used 6- or 9-bit bytes. The C standard still only promises at least 8 bits (CHAR_BIT), and network standards say octet when they mean exactly 8. It rarely matters in practice, but it's a good example of how many "facts" in computing are agreements that could have gone another way. (Chapter 6.)

Applying it

Code walkthrough

The chapter shows two exit codes without explaining where they come from: python3 missing.py returned 2, and a crashed Java program prints a stack trace. Both come from small, readable pieces of C code in the language launchers. Reading them connects the chapter's ideas (exit codes, main, stderr) to production code that runs billions of times a day.

CPython: why a missing file exits with 2 and a crash with 1

File: Modules/main.c in CPython, tag v3.13.0. This function runs a script file:

C
static int
pymain_run_file_obj(PyObject *program_name, PyObject *filename,
                    int skip_source_first_line)
{
    ...
    FILE *fp = _Py_fopen_obj(filename, "rb");
    if (fp == NULL) {
        // Ignore the OSError
        PyErr_Clear();
        PySys_FormatStderr("%S: can't open file %R: [Errno %d] %s\n",
                           program_name, filename, errno, strerror(errno));
        return 2;
    }
    ...
    struct _Py_stat_struct sb;
    if (_Py_fstat_noraise(fileno(fp), &sb) == 0 && S_ISDIR(sb.st_mode)) {
        PySys_FormatStderr("%S: %R is a directory, cannot continue\n",
                           program_name, filename);
        fclose(fp);
        return 1;
    }
    ...
    int run = _PyRun_AnyFileObject(fp, filename, 1, &cf);
    return (run != 0);
}

How it maps onto the chapter:

  • The chapter's message, python3: can't open file '/home/asha/projects/hello/missing.py': [Errno 2] No such file or directory, is that PySys_FormatStderr format string, filled in. It goes to stderr (the function's name says so), which is why > output.txt wouldn't capture it.
  • return 2 is the exit code the chapter saw with echo $?. Two different 2s appear in that line: [Errno 2] is the operating system's error number for "no such file" (ENOENT), while the exit code 2 is CPython's own choice for "I couldn't even start your script". They're unrelated.
  • return (run != 0) means any script that dies from an uncaught exception exits with 1.
  • sys.exit(n) or raise SystemExit(n) is handled separately (by _Py_HandleSystemExit, earlier in the file) and passes your own n through.

Checked on Python 3.13:

Terminal
$ python3 nofile.py 2>/dev/null; echo $?
2
$ python3 -c '1/0' 2>/dev/null; echo $?
1
$ python3 -c 'raise SystemExit(3)'; echo $?
3

The JDK launcher: how java Hello finds and calls main

File: src/java.base/share/native/libjli/java.c in OpenJDK, tag jdk-21-ga. The java command is a small C program. Its JavaMain function starts the JVM, then:

C
    mainClass = LoadMainClass(env, mode, what);
    CHECK_EXCEPTION_NULL_LEAVE(mainClass);
    ...
    switch (mainType) {
    case 0: {
        mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
                                           "([Ljava/lang/String;)V");
        CHECK_EXCEPTION_NULL_LEAVE(mainID);
        (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
        break;
        }
    case MAIN_WITHOUT_ARGS: { ... "main", "()V" ... }
    case MAIN_NONSTATIC:    { ... NewObject(...) then "main", "([Ljava/lang/String;)V" ... }
    case MAIN_NONSTATIC | MAIN_WITHOUT_ARGS: { ... }
    }

    /*
     * The launcher's exit code (in the absence of calls to
     * System.exit) will be non-zero if main threw an exception.
     */
    ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1;

    LEAVE();

How it maps onto the chapter:

  • "([Ljava/lang/String;)V" is the JVM's internal spelling of void main(String[] args). [ means array, Ljava/lang/String; means the String class, and V means void. This is why the chapter's hello world must be exactly public static void main(String[] args): the launcher looks the method up by that name and signature.
  • JDK 21 already has the four main shapes that JEP 512 later made final in JDK 25: static or instance, with or without String[] args. In JDK 21, the three new shapes only work with --enable-preview, which is why Simple.java failed above.
  • ret = … ? 0 : 1 is why a Java program that crashes with an exception (like the chapter's ArrayIndexOutOfBoundsException) exits with 1. The stack trace itself is printed to stderr by the uncaught-exception handler before this point.
  • If the class can't be found, LoadMainClass fails, and the message comes from sun/launcher/resources/launcher.properties: Error: Could not find or load main class {0} / Caused by: {1}: {2}.

Checked on JDK 21:

Terminal
$ java Boom; echo $?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 1
	at Boom.main(Boom.java:1)
1
$ java Nope; echo $?
Error: Could not find or load main class Nope
Caused by: java.lang.ClassNotFoundException: Nope
1

Read it yourself

  1. In java.c, what happens to the exit code if main calls System.exit(3)? (Hint: read the comment's first words again.)
  2. In main.c, what exit code does python3 somefolder give, and why is it different from a missing file?

Debugging drills

D1. The C averaging program accepts "12abc"

Your C version of the chapter's averaging program gets this input:

Terminal
$ printf '120\n12abc\n80\n0x10\nnan\n1e400\n  7  \n\n' | ./avg_c
count=7 total=nan average=nan

The Python version skips 12abc, 0x10 and 1e400. Find out why C counted 7 values and produced nan, then fix the C program so it accepts only plain decimal numbers (surrounding spaces allowed) and skips everything else with a message showing the line.

D2. "Could not find or load main class", for a class that's right there

A teammate's first Java file, src/in/tiffinbox/Hello.java:

Java
package in.tiffinbox;

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello from a package");
    }
}

They compile and run it from the folder the file is in:

Terminal
$ cd src/in/tiffinbox
$ javac Hello.java
$ ls
Hello.class  Hello.java
$ java Hello
Error: Could not find or load main class Hello
Caused by: java.lang.NoClassDefFoundError: Hello (wrong name: in/tiffinbox/Hello)

Hello.class is right there. Explain the message, and run it correctly.

D3. The build that "passes" with a compile error

A build script that saves its compiler output to a log:

Shell
#!/bin/bash
javac Broken.java 2>&1 | tee build.log
echo "build finished"

Broken.java contains public class Broken { int x = "three"; }. The CI system marks the step green:

Terminal
$ bash build.sh
Broken.java:1: error: incompatible types: String cannot be converted to int
public class Broken { int x = "three"; }
                              ^
1 error
build finished
$ echo $?
0

Explain why the step passes, and fix the script so a compile error fails it.

D4. A script that works on Windows and fails in WSL

You write greet.sh in a Windows editor and run it in WSL:

Terminal
$ bash greet.sh
hello world
greet.sh: line 4: cd: $'/tmp\r': No such file or directory
$ echo $?
1

The file says cd /tmp on line 4, and /tmp exists. Find the cause and fix it.

Career-oriented

Interview prep

Each question comes with How to get there: the way of thinking that produces a strong answer, so you learn the method and not just this answer. Use it, answer aloud or in writing, then open the hints and the solution to compare.

Mid level

Q1. What happens, step by step, between typing python3 hello.py in a terminal and seeing Hello, world!?

How to get there. The spine is a timeline split by who acts: the shell, the OS, the interpreter, then the terminal. For each actor ask: what does it receive, what does it do, and what can go wrong here? The chapter gives you every piece (arguments, paths, standard streams, exit codes); the skill being tested is putting them in order and naming the owner of each step. End with the exit code, because that's where control returns to the shell.

Q2. Compare compiling, interpreting and JIT compilation. Where does each spend time, and when does a type error show up?

How to get there. Don't define the three terms one after another. Build a small grid in your head: the rows are the three approaches, the columns are three moments (build time, startup, steady state after warm-up), plus "when is a type error caught?". Fill in each cell with one phrase, then talk along the columns. Finish with examples where the categories blur (item 11 of Explain it differently, theoretical gap 4). That shows you know the categories are a simplification.

Senior level

Q3. A CI pipeline step is green, but the artifact it produced is broken. How can exit codes lie, and how do you make a pipeline trustworthy?

How to get there. Name the claim first: "an exit code is a program's own report about itself". Then list the ways that report can be wrong, by layer: the shell (pipelines, ignored failures), the tool (exits 0 on failure, exit codes above 255), the wrapper (swallows the child's code) and the process (allowed-to-fail steps). Use drill D3 as the concrete story. The senior move is the last step: don't just fix the scripts, verify the artifact independently.

Q4. The five averaging programs in this chapter disagree about what a number is (see Gaps and misconceptions). Your team is building an API that accepts amounts typed by kitchen staff. How do you decide and enforce what's accepted?

How to get there. Separate three questions the interviewer has deliberately mixed together: what is valid (a specification), who enforces it (client, API, database), and how you prove it (tests). Answer them in that order. Bring evidence: the cross-language table in Gaps and misconceptions shows why "whatever the parser accepts" is not a specification. Mention money in integer units: it shows you're thinking about the domain, not just the parsing.

Staff level

Q5. Forty teams ship internal command-line tools and nightly jobs, and on-call engineers can't tell from logs and exit codes what went wrong. Propose company-wide CLI conventions, and say how you'd get them adopted.

How to get there. Staff questions have two halves: the technical standard and getting 40 teams to follow it. Spend about a third of the answer on the first (streams, exit codes, arguments: the chapter's three ideas) and two thirds on the second: making the right thing the default (templates, libraries), checking it automatically (CI), migrating in priority order, and a metric that shows it worked (time to diagnose a page). An answer that's only a list of conventions reads as senior, not staff.

Q6. A new platform team asks which language to standardise on for services and tooling: Java, Go, Rust or Python. How do you approach the decision?

How to get there. Refuse to pick a winner in the first minute. Structure it as a decision process: requirements (what kinds of software, which numbers matter: startup, memory, latency), constraints (existing code, people, hiring), evidence (a small spike measured in two candidates), decision and its scope (often a short list of languages with clear roles), and how it's revisited (an ADR with triggers). Theoretical gap 1 (every general-purpose language can compute the same things) gives you a strong opening line: the choice is about trade-offs, never capability.