Workbench / Volume 1 Exercises: Foundations of Computing
V1·01
Computers, Programs and Your Toolbox
Exercises for Volume 1, chapter 01: what a computer is, memory versus storage, bits and bytes, programs and languages, compilers, interpreters and the JVM, the terminal, paths, streams, redirection and exit codes, the first programs, tracing and errors. 21 theory questions, 16 programming exercises, 4 cumulative projects, the concepts the chapter leaves out, and 10 senior-level exercises. Hints and solutions unlock only after you've written your own answer.
Start here: how these exercises work
Every chapter's exercises come in four sets, and each targets a different level of the mastery ladder:
| Set | What you do | Proves |
|---|---|---|
| Theory (T) | answer in your own words, from first principles | you can explain why (L1–L3) |
| Programming (P) | build it, run it, measure it, compare with real output | you can use it and see it working (L2–L4) |
| Cumulative (C) | larger tasks combining this chapter with every earlier chapter | you can put the pieces together (L3–L5) |
| Senior (S) | production problems: failures, scale, security, operations, teaching others | you can design, diagnose and operate it (L4–L6) |
Between the programming and senior sets, What the chapter leaves out explains concepts the chapter skips or simplifies that a senior engineer is expected to know. The senior exercises build on them.
How the answers are locked.
Each exercise has an answer box (saved as you type, and synced to your account where available). Nothing is revealed until you've worked:
- Hint 1 unlocks once you've written at least 60 characters of your own answer.
- Hint 2 unlocks once you've used hint 1: your answer must grow or change by at least 40 more characters.
- The solution unlocks after another 40 characters and two minutes of thinking time after hint 2.
- After reading it, rate yourself honestly (got it, partly, missed it). Tick Done only when you could do the exercise again without help.
Solutions are encoded in the page, so they don't appear in search or when you scroll. You can always break the lock by reading the page source; the lock is there to stop the reflex of peeking, not to fight you.
The exercises use everyday situations: a payment app, a phone's storage, a log file, a crashed editor, a server being restarted. Programming exercises are mostly in Java, with Python, C or the shell where they show something Java can't. Every programming solution shows real output from running it on a Linux machine (Java 21, Python 3.13, GCC 13). Your timings will differ; the patterns shouldn't.
A good theory answer is two to five sentences that someone who hasn't read the chapter could follow. If yours needs the book's exact wording, you've memorised rather than understood.
Coverage map. Every part of the chapter is exercised at least twice:
| Chapter component | Exercises |
|---|---|
| input, processing, storage, output; the stored-program idea | T1, T2, C1 |
| CPU, RAM, storage, I/O, OS; the kitchen model | T3, T4, P6, S6 |
| volatile vs persistent storage | T5, P6, P7, C3, S2 |
| bits, bytes, how many patterns | T6, P4, P3 |
| KB vs KiB, units | T7, P5, S5 |
| text, images, sound and programs as numbers; interpretation and types | T8, T9, T10, P3, P8, C1, S4 |
| algorithms, unusual cases, bugs | T11, T12, P12, C4 |
| machine code, compilers, interpreters, the JVM | T13, T14, P9, P10, P14, S7 |
| choosing a language | T21, C4 |
the shell, files, folders, paths (absolute, relative, . .. ~), extensions |
T15, P1, P16, C2, S8 |
| commands: pwd, ls, cd, mkdir, cat, echo, cp, mv, rm, man | P1, P15 |
stdin, stdout, stderr, redirection (< > >> 2> |) |
T16, P2, P15, C2, S3 |
exit codes, && and || |
T17, P2, P11, C2, S1 |
| command-line arguments and quoting | T18, P15 |
| installing tools, package managers, editors, plain text | P16, S9 |
| the edit, build, run loop | P9, P10, P14 |
hello world, line by line (main, functions, strings, \n, blocks, indentation) |
T18, P9 |
| variables, types, loops, decisions, conversion, error handling, end of input | T19, P11, P15, C1 |
| tracing by hand | T19, P12 |
| compile-time, run-time and logic errors; reading messages and stack traces | T20, P13, S10 |
Theory: what a computer is
T1. Input, processing, storage, output in an app you use
Take a UPI payment in an app such as Google Pay or PhonePe: you scan a QR code, type ₹250, enter your PIN, and see "Payment successful". List at least two inputs, two kinds of processing, two kinds of storage (one brief, one permanent) and two outputs, on your phone and on the bank's servers.
T2. Why "instructions are data" matters
The chapter says a computer differs from a calculator because its instructions are themselves data. Explain in your own words what that means, and give three consequences you see every day: one useful, one dangerous, and one about how programs get faster while they run.
T3. The kitchen, under pressure
Use the kitchen comparison (CPU = cook, RAM = worktop, storage = pantry, OS = kitchen manager) to explain what happens in each case. Then say where the comparison breaks down.
- You open a 4 GB video file on a laptop with 8 GB of RAM.
- You have 60 browser tabs open and the laptop gets slow.
- Music plays while you type in an editor.
- You press a key.
T4. Why load into memory first? Do the arithmetic
Typical access times: RAM about 100 nanoseconds, an SSD about 100 microseconds, a spinning hard disk about 10 milliseconds. How many RAM accesses fit in the time of one SSD access, and of one disk access? Use the answer to explain why programs load data into memory before working on it, and why databases care so much about keeping data in RAM.
T5. Volatile and persistent, in everyday events
For each event, say exactly what is lost and what survives, and why.
- A power cut while you're editing an unsaved document.
- A power cut one second after you pressed Save.
- Closing a laptop lid (sleep) and opening it the next morning.
- A battery that runs out while the laptop is asleep.
- Restarting a Redis cache that has persistence turned off.
Theory: bits and bytes
T6. How many bits do you need?
n bits can make 2ⁿ patterns. How many bits (whole bits, rounding up) do you need to give a different pattern to each of:
- the 2 states of a light switch;
- the 26 English capital letters;
- 1,000 employees;
- every Unicode character (about 155,000 are assigned);
- every person on Earth (8.2 billion)?
Then explain why computers group bits into 8-bit bytes rather than using exactly the number of bits each job needs.
T7. The missing gigabytes
You buy a "1 TB" SSD. Windows reports it as about 931 GB. Has the manufacturer cheated? Explain exactly where the difference comes from and calculate the number. Then explain why RAM is sold in sizes like 8 GB and 16 GB that really are powers of two.
T8. Same bits, different meanings
Here are four bytes in binary: 01001000 01101001 00100001 00001010.
- Write each as a decimal number and as hex.
- Decode them as text (A = 65, a = 97; 33 is
!; 10 is newline). - Read the same four bytes as one 32-bit whole number (first byte most significant). Roughly how big is it?
- What decides which of these interpretations is "right"?
T9. How big is a photo, uncompressed?
A phone screenshot is 1920 × 1080 pixels; each pixel stores red, green and blue at 1 byte each.
- How many bytes is the raw image? Convert to MB and MiB.
- The same screenshot saved as PNG is about 300 KB, and a photo saved as JPEG is about 1 MB. Without knowing the algorithms, explain from first principles how a file can be smaller than its raw pixels.
- Why is a screenshot of mostly white text much smaller as a PNG than a photo of a forest?
T10. How many bytes is a song?
CD audio measures air pressure 44,100 times per second, stores each measurement as a 16-bit number, and has 2 channels (stereo).
- How many bytes does one minute take? A four-minute song?
- Why 44,100 per second? (Hint: humans hear up to about 20,000 Hz, and a wave needs at least two samples per cycle to be captured.)
- What is lost when a smooth sound wave becomes these numbers?
Theory: programs and languages
T11. An algorithm, with every unusual case
Write a plain-language algorithm (numbered steps, no programming language) that finds the second-largest number in a list. Then list every unusual input it must handle and say what your algorithm does with each.
T12. Make tea, literally
Rewrite "make a cup of tea" as instructions for a machine that has no common sense. Include: the exact quantities, how the machine knows the water has boiled, and what to do in at least four failure cases. Then name the three programming constructs your instructions use (from chapter 01's second program).
T13. When is a typo discovered?
You misspell a variable name inside an if branch that runs only on 29 February. When is the mistake discovered in C, Java and Python, and what does that imply for testing in each? Explain using compiler, interpreter and JVM.
T14. Why one executable doesn't run everywhere
You compile hello.c on an Intel laptop running Linux and copy the file to (a) another Intel Linux laptop, (b) a Mac with an Apple M-series chip, (c) a Windows PC. Which will run it, and why? Now do the same with Hello.class from javac. Explain the difference from first principles.
T21. Which language, and why?
For each job, pick one of the chapter's seven languages (C, C++, Java, Go, Rust, Zig, Python) and justify the choice with the trade-offs it makes (speed, safety, simplicity, ecosystem, how it's translated). Then say what you'd lose with the runner-up.
- A script that renames 3,000 photos by the date they were taken, run once.
- The backend for a bank's account service, maintained by 40 engineers for 10 years.
- Firmware for a smart switch with 64 KB of memory.
- A command-line tool your team installs on Linux, macOS and Windows as a single file.
- A browser's image decoder, which reads untrusted files from the internet.
- A data analyst's weekly report on 2 million rows.
Theory: the terminal
T15. Resolve the paths
Your shell is in /home/asha/projects/hello, and your home folder is /home/asha. Write the absolute path each of these refers to:
hello.py./hello.py../../notes.txt../hello/../hello/hello.py~/projects/tmp/../home../../../..
Then explain why scripts that use relative paths sometimes work when you run them from one folder and fail from another.
T16. Where does each line go?
Streams is a program that prints normal result line to standard output, prints diagnostic line to standard error, and exits with the number given as its argument. For each command, say what appears on the screen, what ends up in each file, and what echo $? would print:
java Streams 3 > out.txt 2> err.txtjava Streams 0 2>/dev/null | tr a-z A-Zjava Streams 0 | wc -ljava Streams 0 2>&1 >/dev/null | wc -l(careful: order matters)java Streams 0 && echo ran second, thenjava Streams 1 && echo never, thenjava Streams 1 || echo fallback ran
T17. Exit codes as a contract
Explain why exit codes exist, given that a program can print "error" on screen. Then describe a real situation in a build or deployment script where a wrong exit code (a program that prints an error but exits with 0) would cause damage.
Theory: first programs and errors
T18. Every word of Java's hello world
Explain every word and symbol of this program, saying what would happen if each were removed or changed:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
T19. Trace it before you run it
Using the chapter's averaging program, fill in a trace table (line read, is it a number?, count, total) for this input, one value per line: 42, 4O (four and a capital letter O), an empty line, -2, 7.5. What does the program print? Then predict the output for the input 1e3, nan, 5, and explain what's wrong with the result.
T20. Classify the error
For each, say whether it's a compile-time, run-time or logic error, which line to look at, and how you'd fix it:
- C:
err.c:5:5: error: expected ',' or ';' before 'printf' - Java:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at Err.main(Err.java:4) - A Python program averaging
[120, 80, 150]printsAverage: 116.66666666666667, and you expected116.67. - A Java loop
for (int i = 1; i <= scores.length; i++) total += scores[i];crashes. - An average of
[10, 20]prints15.0in Python but15in a Java version that usesint totalandint count. With[10, 15], Java prints12. - Python:
IndentationError: unexpected indent
Programming exercises
P1. Build a folder tree from the terminal
Using only pwd, mkdir, cd, echo, ls, cp, mv, cat and rm, starting in your home folder, create this tree, using relative paths for half the commands and absolute paths for the other half:
~/ex01/
├── notes/
│ └── today.txt (containing: "bits, bytes, paths")
└── code/
├── java/
└── python/
└── hello.py (print("Hello from ex01"))
Then: copy today.txt to code/, rename the copy readme.txt, run hello.py from ~ and from inside code/python, list everything with ls -laR ~/ex01, and delete the copy. Finally, answer: what did ls -a show that ls didn't, and why do those entries exist?
P2. Standard streams and exit codes, measured
Write Streams.java: it prints one line to standard output, one line to standard error, and exits with the code given as its first argument (default 0). Then run every command in T16 and confirm each prediction.
P3. A bits explorer
Write Bits.java that, for the numbers 0, 1, 65, 72, 105, 255 and 256, prints each in binary and hex and, where it's a printable character, as a character. Then make it print the UTF-8 bytes of a string given as an argument. Run it with Hi and with ₹100. Finally print (byte) 200 and explain the surprising result.
P4. Count every pattern
Write a program (Java or Python) that takes n and prints every n-bit pattern in order, then the count. Run it for n = 1, 2, 3 and 8 (print only the count for 8). Confirm the count is 2ⁿ, and explain from the printed list why each extra bit doubles the count.
P5. A units converter that doesn't lie
Write a function human(bytes, base) that converts a byte count to the largest sensible unit, with base 1000 (KB, MB, GB, TB) or 1024 (KiB, MiB, GiB, TiB), to two decimals. Test it on 999; 1,024; 1,000,000; 1,048,576; the raw screenshot from T9; one minute of CD audio from T10; and a "1 TB" drive.
P6. Feel the difference between memory and storage
Write a Python (or Java) program that:
- builds 200 MiB of data in memory and copies it;
- writes it to a file, then calls
fsync; - reads it back;
- makes 200 tiny writes (a few bytes each), calling
fsyncafter each; - reads 1,000,000 single bytes from the in-memory data.
Time each step. Explain which numbers measure RAM, which measure the OS's cache, and which measure the device. What does step 4 tell you about logging every event durably?
P7. Prove that memory forgets
Write Counter.java: every 100 ms it increments an in-memory counter and a counter stored in count.txt (read at start-up), writing the file atomically: write count.txt.tmp, then rename it over count.txt. Start it, kill it with kill -9 after two seconds, start it again, kill it again. What does each start print, and what does the file hold? Why the temporary file and the rename?
P8. Look at files as bytes
- Create a file with
printf 'Hi\nA\n' > t.txtand dump it withod -A d -t x1 -c t.txt(orxxdif installed). Explain every byte. - Compile the C hello world and find the text
Hello, world!inside the executable withstrings hello_c | grep Hello. - Print the first 4 bytes of the executable and of
Hello.class(head -c 4 FILE | od -A n -t x1 -c). What are they for? - Run
fileon both.
P9. Three ways to translate one program
Write hello world in C, Java and Python. Then look at what each translator actually produces:
- C:
gcc -O0 hello.c -o hello_c, thenobjdump -d hello_c | awk '/<main>:/,/ret/' - Java:
javac Hello.java, thenjavap -c Hello - Python:
python3 -m dis hello.py
Compare the three listings. Who runs each one? What surprised you in the C version?
P10. When does each language notice a mistake?
Write the same tiny program in Python and Java: print started; if the program received an argument, print a misspelt variable totl; print finished. Compile (Java) and run each with and without an argument. Record what happens and the exit codes.
P11. A sturdier averaging program
Extend the chapter's averaging program (in Java) to:
- also report minimum and maximum;
- accept
1,234(thousands separators) and surrounding spaces; - reject
NaNandInfinityeven though the parser accepts them; - print skipped lines to standard error with their line numbers;
- exit with 0 if all lines were valid, 2 if some were skipped, 1 if there were no numbers at all.
Test it with input from a pipe and from a file, and check each exit code.
P12. Implement and test the second-largest algorithm
Implement T11's algorithm in Java as static OptionalInt secondLargest(int[] xs), and write a main that checks it against every case in T11's table (empty, one element, all equal, duplicate largest, negatives, ascending, descending), printing PASS or FAIL for each.
P13. Break it on purpose: an error collection
Create each of these mistakes deliberately, run or compile, and record in a table: language, the exact first line of the message, the kind (compile-time, run-time, logic), the line it points to, the real location of the mistake, and the fix.
- C: missing semicolon (the chapter's example).
- C: use an undeclared variable.
- Java: call
scores[3]on a 3-element array. - Java: divide an
intby zero, then adoubleby zero. (One of them doesn't fail.) - Python: misspell a name.
- Python:
int("12a"). - Python: mix tabs and spaces for indentation.
- Any language: a program that should print the average of 10 and 15 but prints 12.
P14. Compiled, JIT-compiled, interpreted: measure it
Write the same loop in C, Java and Python: sum i % 7 for i from 0 to 99,999,999 and print the sum. Time each with time (build C with gcc -O2, and also -O0). Check all three print the same sum. Explain the ranking from what you saw in P9.
P15. Arguments, standard input and end of input
Write Greet.java:
- if it gets command-line arguments, it prints how many it got and lists them;
- otherwise it reads names from standard input, one per line, until the input ends, prints
hello, NAMEfor each, and prints the number of names to standard error.
Then predict, and only then run, what each of these prints:
java Greet Asha Ravijava Greet "Asha Ravi"java Greet *.txt(in a folder containing a few.txtfiles)java Greet '*.txt'java Greet $HOME '$HOME'java Greet < names.txt, wherenames.txtholds two namesjava Greet < names.txt >> log.txt 2>/dev/null, run twice, thenwc -l < log.txtjava Greet, typing two names and then pressing Ctrl+D (Linux/macOS) or Ctrl+Z, Enter (Windows)
Finally, look up man bash (search for "QUOTING" by typing /QUOTING) or help for your shell, and explain who turned *.txt into file names: Java or the shell?
P16. Why code needs a plain-text editor
Save the line print("Hello") twice: once as hello.txt from a plain-text editor, once as hello.docx from Word, LibreOffice or Google Docs (download as .docx). Then compare:
- the two file sizes;
- the first four bytes of each (
head -c 4 FILE | od -A n -c); - what
filesays about each; - what happens with
python3 hello.txtandpython3 hello.docx; - what's inside the .docx (
unzip -l hello.docx, or Python'szipfile).
Explain why the chapter says word processors don't work for code.
Cumulative projects (chapters so far: 01)
Each chapter's cumulative set combines the new chapter with every earlier chapter. Chapter 01 is the first, so these projects combine every part of it; from chapter 02 onwards they'll also draw on the earlier chapters' material.
C1. Your own wc, and what it reveals about text
Write Wc.java, which reads all of standard input and reports: lines, words, bytes, Java chars (UTF-16 units) and Unicode code points. It should exit 0 on success and 1 if reading fails (print the reason to stderr). Test it on a file containing Hello, world! and a line with Telugu text and an emoji, compare its output with the real wc -l -w -c -m, and explain every difference between the three "lengths".
Combines: input, processing and output; bits and bytes; stdin and redirection; exit codes; error handling; text as numbers.
C2. A pipeline that fails safely
Write a shell script report.sh that:
- generates a test file of 1,000 lines with
seq 1 1000, with three non-numbers inserted (usesedorecho >>); - runs your
Statsprogram from P11 on it, sending results toreport.txtand errors toerrors.log; - stops with a clear message if
Statsexits 1, warns and continues if it exits 2, and printsOKif it exits 0; - finally prints the report and the number of error lines.
Run it once with the bad lines and once without. Then run it from a different folder and fix whatever breaks.
Combines: the terminal, paths, standard streams, redirection, exit codes, the averaging program, and error handling.
C3. A durable counter that survives a power cut (almost)
Extend P7's counter so that each update is durable: write the temporary file, fsync it, rename it, then fsync the folder (Java: open the directory with FileChannel.open(dir, StandardOpenOption.READ) and call force(true); this works on Linux). Measure updates per second with and without the fsyncs (remove the sleep for this). Write a short paragraph explaining what each step protects against: process crash, OS crash, power cut.
Combines: memory vs storage, files and paths, volatile vs persistent data, exit codes and errors, and measurement.
C4. One algorithm, three languages, one explanation
Implement "count how many numbers in a file are larger than the average" in C, Java and Python. Each version reads numbers from standard input (one per line, skipping and reporting bad lines to stderr), needs two passes over the numbers (so it must keep them in memory), prints the count, and exits 0 or 1 as in P11. Generate a 10-million-line input with seq, check that all three agree, and time them.
Then write a one-page explanation covering: where the numbers live while the program runs and roughly how many bytes they take in each language; why the program must hold them in memory rather than re-reading the input; how each language's translation (P9) explains the timings; and which unusual inputs each version handles and how.
Combines: everything in the chapter.
What the chapter leaves out
Chapter 01 is an on-ramp, so it simplifies. These are the ideas a senior engineer is expected to know that it skips or glosses over. Most get full treatment later in Volume 1 (noted under each); what's here is enough to reason with now, and the senior exercises use all of it. Tick each one when you could explain it to a colleague.
Processes, signals and the full meaning of exit codes
The chapter treats a program as something that runs and returns 0 or not. In reality a running program is a process: the OS's record of a program in execution, with its own memory, open files, current directory, environment variables and a process ID (PID). Processes are created by other processes (your shell starts java), and they end in one of two ways: they exit with a code, or they're terminated by a signal.
A signal is a small notification the OS delivers to a process: SIGTERM ("please shut down": what kill PID, systemd and Kubernetes send first), SIGINT (Ctrl+C), SIGKILL (kill -9: the OS removes the process immediately; it can't be caught, so no cleanup runs), SIGHUP (terminal closed), SIGSEGV (invalid memory access). A process can catch most signals and clean up; Java runs its shutdown hooks on SIGTERM and SIGINT.
When a signal kills a process, the shell reports exit code 128 + the signal number. So the codes you'll see in production logs mean:
| Code | Meaning |
|---|---|
| 0 | success |
| 1 | general failure (Java's uncaught exception, Python's uncaught exception) |
| 2 | misuse: bad arguments (Python's "file not found" for the script is 2) |
| 126 | found but not executable (missing chmod +x) |
| 127 | command not found (typo, or not on PATH) |
| 130 | killed by SIGINT (Ctrl+C) = 128 + 2 |
| 137 | killed by SIGKILL = 128 + 9: often the kernel's out-of-memory killer, or Kubernetes "OOMKilled" |
| 143 | terminated by SIGTERM = 128 + 15: a normal stop request |
S1 measures all of these. Deeper: chapter 8 (operating systems).
Buffering at every layer
The chapter says storage "keeps files permanently". Between your print and the disk there are at least three buffers, each a piece of RAM that can be lost:
- Your program's output buffer. C's
stdioand Python buffer output: line by line when writing to a terminal, but in blocks of several KB when writing to a file or pipe. A program killed with SIGKILL, or one that crashes hard, loses whatever is still in that buffer. Java'sSystem.out.printlnflushes on every line, so it behaves differently (S3). - The OS page cache.
write()copies data into kernel memory and returns; the kernel writes it to the device later. A process crash doesn't lose it; an OS crash or power cut does. - The device's own cache. SSDs buffer writes too.
fsync()asks the OS to push its cache to the device and the device to make it durable.
"Flush" (empty layer 1 into layer 2) and "sync" (push layer 2 through layer 3) are different operations. Durable systems do both deliberately (P7, C3, S2). Deeper: chapter 8.
Text is Unicode, not just ASCII
The chapter's "standard code used everywhere" (A = 65) is ASCII, a 1963 standard with 128 characters. What is actually used everywhere now is Unicode (one number for every character in every script) encoded as UTF-8, which keeps ASCII's codes for the first 128 characters and uses 2–4 bytes for everything else (₹ is 3 bytes, P3). So "one character = one byte" is true only for English. Every boundary where text crosses (files, terminals, databases, HTTP, command-line arguments) must agree on the encoding, or you get garbled text. S4 shows Java receiving ???5 instead of ₹5 because the terminal's locale wasn't UTF-8. Deeper: chapter 6 here, and all of Volume 23.
PATH, environment variables, and how the shell finds programs
The chapter runs ./hello_c without explaining the ./. When you type a command name without a slash, the shell searches the folders listed in the PATH environment variable, in order, and runs the first match (echo $PATH; which java or type java shows which one wins). The current folder isn't on PATH (on purpose: otherwise a malicious file named ls in a downloaded folder would run instead of the real ls), so you must say ./hello_c.
Environment variables are named strings every process inherits from its parent: PATH, HOME, LANG (locale and encoding), JAVA_HOME, and your own (DATABASE_URL). They're the standard way to configure programs without changing code, which is why containers and cloud platforms configure apps through them. Two consequences: a changed PATH explains "it works in my terminal but not in cron" (cron has a minimal environment), and secrets in environment variables are visible to the process's children and sometimes in crash dumps.
Permissions, ownership and least privilege
The chapter's ls -l output shows -rw-r--r-- 1 asha asha without explaining it. Each file has an owner, a group, and permission bits for three audiences (owner, group, others): read, write, execute. -rw-r--r-- means the owner can read and write; everyone else can only read; nobody can execute. chmod +x script.sh adds execute permission (without it, running the script gives exit code 126). sudo runs one command as the administrator (root): powerful, so used only when needed. Running services as root, or making files world-writable to "fix" a permission error, are classic security mistakes. Deeper: chapter 6 explains the octal form (chmod 644) and chapter 8 the OS side.
Fixed-size numbers overflow
The chapter says a byte holds 0 to 255, but most languages also use fixed-size integers whose limits matter in real code: Java's int is 32 bits (−2,147,483,648 to 2,147,483,647), long 64 bits. Arithmetic past the limit wraps around silently in Java, C and Go: 3 GiB in an int becomes −1,073,741,824 (S5). File sizes, durations in milliseconds and counters are the usual victims. Java's byte is also signed (−128 to 127), which surprises everyone once (P3). Deeper: chapters 2 and 6.
Above RAM and beneath it: caches and virtual memory
The kitchen has three levels; real machines have more. Above RAM sit the CPU's registers and caches (L1, L2, L3), much faster and much smaller, which is why the order you access memory in can change speed tenfold. Beneath it, the OS gives every process virtual memory: each process sees its own private address space, which the OS maps to physical RAM and, when RAM runs short, to swap space on disk. That's why T3's 60 browser tabs slow down rather than crash, and why one process can't read another's memory. Deeper: chapters 7 and 8.
Dependencies, versions and reproducible environments
The chapter installs tools with apt and moves on. In real projects, the hard problems are which version and whose machine: code compiled for Java 21 won't run on a Java 17 runtime (S9); a library update changes behaviour; a script works on your laptop and fails in CI. The tools that solve this: version managers (SDKMAN!, pyenv), build tools that pin versions (Gradle and Maven for Java, with toolchains; lock files such as package-lock.json or poetry.lock), virtual environments for Python (python3 -m venv, rather than installing into the system Python), and containers that package the runtime with the app. The rule: the build should produce the same result on any machine, from versions written in the repository. Deeper: Volume 8 (DevOps).
Trusting the toolchain
The chapter's Rust install runs curl … | sh: it downloads a script from the internet and runs it immediately, with your permissions. That's normal practice for some well-known installers, but it means you're trusting the server, the network path and everyone who can change that script. The safer habits: download first and read or checksum it; prefer the OS package manager or signed packages; pin versions; and for company builds, use an internal mirror. Supply-chain attacks (a compromised library or installer) are among the most damaging security incidents because they reach everyone downstream. Deeper: Volume 10 (security).
Debuggers and observability
The chapter teaches reading error messages, which is essential, but not the two tools seniors use most when messages aren't enough. A debugger (IntelliJ or VS Code breakpoints, jdb, gdb) pauses a running program so you can inspect every variable and step line by line, which is far faster than adding prints. Logs, metrics and traces are how you debug programs you can't pause: those running on servers for real users. Write logs to standard error (or a logging system), with enough context (an order ID, a user ID) to reconstruct what happened, and chained exceptions that keep the root cause ("Caused by:", S10). Deeper: chapter 2 here (debugging), Volume 9 (observability).
A process's working directory, and path traversal
T15 showed relative paths resolve against the process's current working directory. For services this is often surprising: systemd, cron, Docker (WORKDIR) and IDEs each choose a different one. Servers should build paths from configured absolute locations.
The security side: whenever a path includes user input (a file name in a URL, an upload's name), an attacker can send ../../etc/passwd and walk out of the intended folder. This is path traversal, one of the most common web vulnerabilities. The defence is to resolve and normalise the full path, then check it's still inside the allowed folder (S8). Deeper: Volume 10.
Senior exercises
These assume the material above. Each is a situation a senior engineer meets in production or in a design review: the answer isn't only "what happens" but "what would you do about it, and how would you explain it to your team".
S1. Exit codes from a Kubernetes incident
Your Java service's pods restart several times a day. The logs show exit codes 143, 137 and once 127, and the release notes for the base image mention "removed curl". Write Graceful.java, which registers a shutdown hook that prints a message, prints its PID, and sleeps for a minute. Then, from a shell, measure the exit code when you stop it with kill -TERM, kill -KILL and Ctrl+C (or kill -INT); also measure what the shell returns for a command that doesn't exist and for a script without execute permission.
Use your results to explain each production exit code, what probably caused it, and what you'd change in the service or its configuration.
S2. How many durable writes per second?
A payments service must record each payment durably before replying "success". A colleague proposes writing each payment to a log file and calling fsync after each one. Measure, on your machine, how many records per second you can write when you fsync after every record, after every 10, and after every 100. Then propose a design that is durable and fast, and say what it costs.
S3. The logs that vanished
A nightly Python job is run by cron with its output redirected to a log file: python3 job.py > job.log. When the job hangs and the operator kills it, job.log is empty, although the job printed several progress lines before hanging. The same thing written in Java leaves the lines in the log.
Reproduce it: write a script that prints five progress lines 0.3 s apart and then sleeps; redirect its output to a file; kill it with kill -9 after two seconds; count the lines in the file. Repeat with kill -TERM, with python3 -u, with an equivalent C program, with stdbuf -oL in front of the C program, and with Java. Explain the results and give the team a rule.
Careful: if your environment sets PYTHONUNBUFFERED=1 (some containers and IDEs do), Python won't buffer. Run with env -u PYTHONUNBUFFERED to see the default.
S4. The ₹ that became ???
A Java tool that takes a product name as a command-line argument works on developers' laptops, but in the CI container java Cs "₹5" receives ???5. Write Cs.java, which prints Charset.defaultCharset(), the system properties stdout.encoding and sun.jnu.encoding, and the first argument with its length. Run it with LANG=C LC_ALL=C and with LANG=C.UTF-8 LC_ALL=C.UTF-8. Explain what changed, why Java 18's switch to UTF-8 as the default charset didn't prevent it, and how you'd fix it for every service in the company.
S5. Overflow in production
Without running anything, predict what this Java code prints, then run it:
int threeGiB = 3 * 1024 * 1024 * 1024;
long ok = 3L * 1024 * 1024 * 1024;
int ms = 25 * 24 * 60 * 60 * 1000; // 25 days in milliseconds
Math.multiplyExact(3, 1024 * 1024 * 1024);
Then: (a) explain the two wrong results bit by bit; (b) find two places in a typical Java backend where this bug could hide (think upload sizes, timeouts, counters, IDs); (c) propose how a team prevents the whole class of bug, not just these two instances.
S6. The service that ran out of memory twice
Your Java service runs in a container with a 512 MiB memory limit. Sometimes it dies with java.lang.OutOfMemoryError: Java heap space in the logs; other times it disappears with exit code 137 and no Java error at all. Write Hog.java, which keeps allocating 10 MiB arrays and holding on to them. Run it with -Xmx64m, then with -Xmx64m -XX:+ExitOnOutOfMemoryError, and record the output and exit code of each. Explain the two production symptoms, and how you'd configure the JVM and the container.
S7. Why the first requests are slow
After every deploy, your Java service's first few hundred requests are noticeably slower, and the latency alert fires briefly. Write Warm.java: a method that does a fixed amount of arithmetic work, called ten times, timing each call with System.nanoTime(). Run it normally, then with -Xint (interpreter only). Use the results to explain the alert, and list at least four ways to fix or hide it, with the trade-off of each.
S8. Serving files without leaking secrets
A teammate's endpoint serves menu files: GET /files?name=menu.txt reads public/ + name. Write a Java program with two methods, naive(name) (reads Path.of("public/" + name)) and safe(name), and test both with menu.txt, ../secret.txt, ./../secret.txt, /etc/hostname and sub/../../secret.txt (create public/menu.txt and a secret.txt beside public/). Make safe reject everything outside public/. Then list what else a production version must handle.
S9. "It works on my machine"
A teammate compiles a library with JDK 21 and publishes it; another team's service, running on Java 17, fails at start-up. Reproduce the evidence: compile Hello.java with javac -d r21 Hello.java and with javac --release 17 -d r17 Hello.java, then read the class-file major version (bytes 7 and 8 of the file: od -A n -t u1 -j 6 -N 2 r21/Hello.class). Find which Java version each number means and what error Java 17 gives for the newer one. Then write the half-page policy you'd propose so this can't happen again, covering compilers, runtimes, build tools and the base image.
S10. Find the root cause, then teach it
Run this program from a folder containing prices/idli.txt (with the text 40) but no prices/dosa.txt:
import java.nio.file.*;
public class Checkout {
static String loadPrice(String item) {
try { return Files.readString(Path.of("prices", item + ".txt")).trim(); }
catch (java.io.IOException e) { throw new IllegalStateException("price lookup failed for " + item, e); }
}
static long total(String... items) {
long t = 0;
for (String i : items) {
try { t += Long.parseLong(loadPrice(i)); }
catch (RuntimeException e) { throw new RuntimeException("checkout failed", e); }
}
return t;
}
public static void main(String[] a) { System.out.println(total("idli", "dosa")); }
}
- From the stack trace alone, give the root cause, the exact line where it started, and the chain of events.
- A junior engineer "fixes" a similar bug by changing
throw new RuntimeException("checkout failed", e)tothrow new RuntimeException("checkout failed"), because "the trace is too long". Write the review comment you'd leave (chapter 02 of Volume 24 has the style), explaining what's lost. - Write a five-step guide, for new team members, to reading any Java stack trace.