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

Workbench / Volume 1 Exercises: Foundations of Computing

V1·02

Programming Fundamentals and Paradigms

Exercises for Volume 1, chapter 02: values, types and variables; expressions, operators, division and conversions; control flow and cleanup; functions, parameter passing and closures; recursion and the stack; compound data, modules, interfaces, polymorphism and generics; error handling; state, immutability, value and reference semantics and ownership; I/O and serialization; testing, debugging and undefined behaviour; paradigms and type systems. 20 theory questions, 18 programming exercises, 4 cumulative projects with chapter 01, the concepts the chapter leaves out, and 10 senior-level exercises.

65 exercises · ~28 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The four sets and the locking work as in chapter 01's page: write at least 60 characters of your own answer to unlock hint 1, extend it by 40 characters to unlock hint 2, and extend it again and wait two minutes for the solution. Every programming solution shows real output from running it (Java 21, Python 3.13, GCC 13, Node 22, on Linux). Where a number depends on the machine (stack depths, timings), the solution says so.

Chapter 02 compares six languages. These exercises use Java for most programming work, with Python where its semantics differ instructively, and C where only native code shows the effect (layout, linking, undefined behaviour). You don't need Go, Rust or Zig installed; where they matter, the questions ask you to reason about them.

Coverage map. Every part of the chapter is exercised at least twice:

Chapter component Exercises
values, types and representation T1, P2, P4
variables, binding and storage; initialisation; constants T2, T3, P17
scope, lifetime, shadowing T3, P17, P5
source to running program: preprocess, compile, link, build T4, P1
expressions vs statements; precedence, associativity, evaluation order T5, P3
arithmetic, integer and floor division, overflow T6, P2, P4
logical, bitwise and comparison operators; short-circuiting T5, P3
conversions and casting T7, P4
conditionals, switch and pattern matching T8, P8
loops, break and continue; structured cleanup (finally, try-with-resources, defer, RAII) T9, P10
functions: anatomy, parameter passing (value, pointer, reference, move) T10, P5
multiple returns, overloading, defaults, variadics T11, P9
first-class functions, closures, higher-order functions T12, P6, P16
recursion, stack frames, tail calls, recursion vs iteration T13, P7, S6
arrays, slices, strings T14, P5, P14
structs and memory layout; enums and sum types; pointers, references and null T14, T15, P4, P8, P18
modules, packages, visibility; dependencies and build tools T16, P1, S9
abstraction, interfaces, kinds of polymorphism, static vs dynamic dispatch T17, P9
generics and their implementation strategies T17, P11
error models, designing errors T18, P10, S2
state, immutability, value vs reference semantics, ownership, aliasing T10, T19, P5, P12, S7
streams, buffering, files, encodings, serialization, schema evolution T20, P13, P14, S3, S8
testing, debugging, undefined behaviour T3, P15, P18, S5, S10
paradigms: imperative, OO, functional, declarative, generic, concurrent, data-oriented T21, P16, S4
type systems: static/dynamic, strong/weak, nominal/structural, inference, null safety T22, P8, P11

Theory: values, variables and the build

T1. Same bits, different types, in a shopping cart

A cart total is ₹1,234.50. Explain how you'd represent it, and why, if the value is (a) shown on screen, (b) stored in a database, (c) sent in a JSON API to a JavaScript app, and (d) used to compute 18% GST. For each, name the type in Java and say what goes wrong with the obvious alternative.

T2. What is a variable, really?

Explain the difference between a name, a binding, a value and a storage location, using these two snippets:

Java
int a = 5;  int b = a;  b = 7;               // Java
List<String> x = new ArrayList<>();  List<String> y = x;  y.add("idli");
Python
a = 5; b = a; b = 7                          # Python
x = []; y = x; y.append("idli")

What are a and x afterwards in each language, and why? What exactly does = do in each case?

T3. Scope, lifetime and initialisation

For each, say whether it compiles or runs, and what it prints or why it fails. Then explain the difference between scope and lifetime with an example where they differ.

  1. Java: static int field; then int local; inside main, then printing both.
  2. Java: a field static int total = 100; and, in main, int total = 5; System.out.println(total + " " + Shadow.total);
  3. Python: a global count = 0 and a function whose body is count += 1.
  4. C: int f(void) { int x; return x; }

T4. From source to running program, and the errors at each step

A C program is in two files, main.c (calls with_gst) and price.c (defines it), with a header price.h. List the four stages from source to a running executable, what each produces, and which kind of error each stage reports. Then: you run gcc main.c and get undefined reference to 'with_gst'. Which stage failed, why, and what's the fix? How does the same problem look in Java?

T5. Evaluation order and short-circuiting

Predict the output, then explain each line. (Assume f(name, v) prints name and returns v.)

Java
int r = f("a", 1) + f("b", 2) * f("c", 3);   System.out.println("= " + r);
int i = 5;  i = i++;                          System.out.println(i);
int j = 5;  int k = j++ + ++j;                System.out.println(k + " " + j);
String s = null;
System.out.println(s != null && s.length() > 3);
System.out.println(s != null & s.length() > 3);
System.out.println(8 >> 1 + 1);

T6. Division in real life

Write the expression that gives the right answer in Java and in Python for each, and explain the wrong answer the obvious expression gives:

  1. Pages needed to show 101 orders, 20 per page.
  2. Average delivery time of 7 orders taking 213 minutes in total.
  3. Converting -1 hour into the range 0–23 (yesterday's 23:00).
  4. Splitting ₹100.00 (10,000 paise) among 3 people so the shares add up exactly.
  5. Detecting whether a + b overflowed for two Java int counters.

T7. Conversions you didn't ask for

Predict, then check with P4: (int) 3.99, (int) -3.99, Math.round(-2.5), (byte) 300, (int) 1e10, (int) Double.NaN, 1 + 2 + "3", "1" + 2 + 3, 'a' + 1, Math.abs(Integer.MIN_VALUE), and a long holding 2⁵³ + 1 converted to double and back. Classify each as a narrowing conversion, a widening one, or an implicit conversion by an operator, and say which ones lose information silently.

Theory: control flow, functions and recursion

T8. Exhaustive decisions

TiffinBox charges a payment fee: UPI 0%, domestic card 1.8%, international card 3.5%, cash 0%. Write the decision three ways (in pseudocode or Java): an if/else if chain on a String type code; a switch on an enum; and a switch over a sealed interface with record patterns. Then a new method, "wallet", is added. What happens in each version, and which is best for code that will live for years?

T9. Cleanup that always happens

A method opens a database connection and a cache connection, runs a query that throws, and both close() methods also throw. Using Java's try-with-resources, describe exactly: the order of closing, which exception the caller receives, and where the other exceptions go. Then explain why return inside finally is dangerous, and compare with Go's defer and C++'s RAII.

T10. How arguments are passed

Predict what each prints, then explain using the words pass by value, reference, and mutation:

Java
static void reassign(int[] arr) { arr = new int[]{99}; }
static void mutate(int[] arr)   { arr[0] = 99; }
static void bump(int n)         { n++; }
int[] arr = {1};  reassign(arr);  System.out.println(arr[0]);
mutate(arr);                      System.out.println(arr[0]);
int n = 1;  bump(n);              System.out.println(n);

Then explain what C (int *p), C++ (int &r) and Rust (passing a Vec by value, i.e. a move) do differently.

T11. Overloading versus overriding

Predict, then explain:

Java
static String describe(Object o) { return "Object"; }
static String describe(String s) { return "String"; }
Object x = "hello";
System.out.println(describe(x));

class Discount { long apply(long p) { return p; } }
class Festive extends Discount { @Override long apply(long p) { return p * 90 / 100; } }
Discount d = new Festive();
System.out.println(d.apply(1000));

Which choice is made at compile time and which at run time? Why does that make public boolean equals(Discount d) (instead of equals(Object o)) a serious bug?

T12. Closures that capture the wrong thing

  1. In Python, what does [f() for f in [lambda: i for i in range(3)]] return, and why? Fix it two ways.
  2. Why does Java refuse to compile int base = 10; base++; Runnable r = () -> System.out.println(base);?
  3. Give one everyday use of closures in real code, and one bug they cause there.

T13. The stack, recursion and denial of service

  1. Explain what a stack frame holds and why recursion depth is limited. Why do Java's measured depths differ between runs and with -Xss?
  2. A JSON parser in your service is recursive (one call per nesting level). An attacker sends [[[[…]]]] nested 50,000 deep. What happens in Java, Python, C and Go?
  3. Give two fixes, and say why "make the stack bigger" isn't one of them.

Theory: data, abstraction and errors

T14. Layout, slices and strings

  1. A C struct { char veg; int price; char spicy; } is 12 bytes, but reordered as { int price; char veg; char spicy; } it's 8. Explain why. Why might that matter for an array of 10 million menu items?
  2. Java String is immutable. Explain three benefits, and the performance trap it creates when building a large string in a loop.
  3. In Go, lines[:2] is a slice sharing the array with lines. Explain the chapter's "disappearing discount" bug: appending to lines[:2] overwrote lines[2].

T15. Null, Optional and sum types

Tony Hoare called null references his "billion-dollar mistake". Explain why null is so error-prone, then compare how Java (Optional, annotations), Kotlin (String?), Rust (Option<T>) and Go (zero values and nil) represent "no value". When should a Java method return Optional, and when shouldn't it?

T16. Modules, visibility and dependencies

  1. Why do languages provide visibility rules (private, package-private, pub, capitalised names in Go, static functions in C)? Give two concrete benefits for a 200,000-line codebase.
  2. Your service depends on library A (which needs jackson 2.15) and library B (which needs jackson 2.17). What does Maven or Gradle do, and what can go wrong at run time?
  3. What's the difference between an API being source-compatible and binary-compatible?

T17. Kinds of polymorphism, and how generics are implemented

Name the four kinds of polymorphism the chapter describes and give a TiffinBox example of each. Then explain the three ways languages implement generics (erasure, monomorphisation, dictionary/vtable passing), name a language that uses each, and give one practical consequence of Java's choice.

T18. Choosing an error model

The chapter describes exceptions (Java, Python, C++), error values (Go, C), and result types (Rust Result, Zig error unions). For each of these situations in a payment service, choose how to signal the problem in Java and justify it:

  1. A user typed an invalid card number (happens thousands of times a day).
  2. The payment gateway timed out (retryable).
  3. The database password in configuration is wrong (at start-up).
  4. A bug: a method received a negative amount that callers should never pass.
  5. "Customer not found" in a lookup by ID.

Use the lab's cost numbers (P10) in your reasoning.

T19. Immutability and ownership

  1. Explain why immutable objects can be shared between threads without locks, and why they make good map keys.
  2. A Java record Order(String id, List<String> items) looks immutable. Show how its items can still change, and fix it.
  3. Explain Rust's ownership rules in three sentences, and which class of bug they eliminate at compile time.

T20. I/O, encodings and serialization

  1. Writing 200,000 lines with an unbuffered FileOutputStream took 115 ms; with a BufferedWriter, 34 ms. strace counted about 200,000 write system calls for the unbuffered run. Explain the difference.
  2. A UTF-8 file containing Crème brûlée, ₹120 read with ISO-8859-1 shows Crème brûlée, â¹120. Explain byte by byte what happened to è.
  3. A v2 producer adds "currency": "AED" to an order message; a v1 consumer reads paise. Describe two ways the consumer can react and the risk in each. What do schema-based formats (Protocol Buffers, Avro) do about this?

Theory: paradigms and type systems

T21. One task, four paradigms

Task: total revenue per kitchen from a list of orders, excluding cancelled ones. Describe how it looks in imperative, object-oriented, functional (streams) and declarative (SQL) style. For each, say what the programmer specifies and what's left to the language or engine, and when you'd choose it. Where do concurrent and data-oriented design change the picture?

T22. Four axes of type systems

Place Java, Python, JavaScript, C, Go, Rust and TypeScript on each axis, with one example of a bug each position catches or allows:

  1. static vs dynamic (when types are checked);
  2. strong vs weak (how much is converted implicitly);
  3. nominal vs structural (what makes two types compatible);
  4. explicit vs inferred (who writes the types).

Then explain why "dynamically typed" doesn't mean "untyped", and why var in Java isn't dynamic typing.

Programming exercises

P1. Build a two-file program by hand, stage by stage

Create price.h (declaring long with_gst(long paise);), price.c (defining it as paise + paise * 18 / 100) and main.c (printing with_gst(10000)). Then run each stage separately: gcc -E main.c | wc -l, gcc -c main.c, nm main.o, gcc main.o -o app (it should fail), gcc -c price.c, nm price.o, gcc main.o price.o -o app, ./app. Record what each step produces and explain the letters T and U in nm's output. Finally, describe the Java equivalent of each stage.

P2. Division and remainders in Java, Python and C

Write a short program in Java, and one-liners in Python and C, that print: 7/2, -7/2, 7%3, -7%3, 7%-3, Java's Math.floorDiv(-7, 2) and Math.floorMod(-7, 3), 7.0/2, 1/0.0, 0.0/0.0; pages needed for 101 items at 20 per page (naive, by formula, and with Math.ceilDiv); and -1 % 24 versus Math.floorMod(-1, 24). Tabulate the results by language and state the rule each language follows.

P3. Evaluation order, side effects and short-circuiting

Write Order.java with a method f(name, v) that prints its name and returns v, and check every prediction you made in T5. Add a null-guard demonstration using && and &, and print 8 >> 1 + 1 and (5 & 3) == 1.

P4. Conversions and equality traps

Write Conv.java and Eq.java to test every conversion in T7, plus these equality cases: two string literals "idli"; a literal versus new String("idli"); a literal versus "id" + suffix built at run time; .equals and .intern(); Integer 127 == 127 and 128 == 128; Integer(128).equals(Long 128); and unboxing a null Integer into an int. Explain each result.

P5. Aliasing in Java and Python

Write Ref.java with the three methods from T10, and run them. Then, in Python, demonstrate: b = a then b.append(3); [[0] * 3] * 3 versus a list comprehension, after setting grid[0][0] = 9; and a function add_item(item, cart=[]) called twice. Explain each with a box-and-arrow diagram (draw it on paper).

P6. Closures, captured variables and higher-order functions

  1. In Python, build [lambda: i for i in range(3)], call each, then fix it with a default argument.
  2. In Java, write a lambda that captures a local base and adds it; then try to modify base after creating the lambda and read the compiler error.
  3. Write a Java higher-order function static <T> T withRetry(int attempts, Supplier<T> action) that calls action until it succeeds or attempts run out, rethrowing the last exception. Test it with a supplier that fails twice then succeeds, counting calls with a captured AtomicInteger.

P7. How deep can you go, and how to stop worrying

Write Depth.java: (a) a method that recurses until StackOverflowError and reports the depth; (b) a recursive and an iterative function that compute the maximum nesting depth of a string of brackets; run both on "[".repeat(50_000) + "]".repeat(50_000). Run with the default stack and with -Xss16m, and run Python's equivalent to hit its limit. Explain why your depth differs from the chapter's 22,142.

P8. Sealed types and exhaustive switches

Write Pay.java with sealed interface Payment permits Upi, Card, Cash, the three as records (Card has last4 and international), and feePaise(Payment p, long amount) using a switch expression with record patterns and a guard: UPI 0, domestic card 1.8%, international card 3.5%, cash 0. Print the fee on ₹1,000.00 for each. Then delete the Cash case and compile.

P9. Overloading, overriding and a broken equals

Write Dispatch.java to check T11: two describe overloads called with an Object-typed string; a Festive subclass overriding apply; and a Discount class with public boolean equals(Discount d) { return true; }. Show what new Discount().equals((Object) other) returns, and the size of a HashSet after adding two new Discount() objects. Then add @Override to the broken equals and read the compiler's message.

P10. Cleanup and the cost of exceptions

  1. Write Res.java: an AutoCloseable Conn whose close() prints and then throws; open db and cache in one try-with-resources, throw RuntimeException("query failed") inside, catch it, and print its suppressed exceptions. Add a method with return 42 in a finally after a throw.
  2. Write Cost.java: a failure detected 50 frames deep, reported one million times as a return code, an Optional, an exception with a stack trace, and an exception without one (super(msg, null, false, false)). Time each after a warm-up round.

P11. What erasure erases

Write Erase.java: compare new ArrayList<String>().getClass() with new ArrayList<Integer>().getClass(); then assign a List<String> to a raw List, add an Integer through it, and read element 0 as a String. Note the compiler warnings, and where the exception appears. Then try writing static <T> T[] make(int n) { return new T[n]; } and read the error.

P12. Immutability that holds, and mutation while iterating

Write record Order(String id, List<String> items). Show that (a) changing the original list after construction changes the record, and (b) o.items().add(...) works. Fix it with a compact constructor using List.copyOf. Compare with Collections.unmodifiableList. Then remove every 2 from ArrayList.of(1, 2, 2, 3) in a for-each loop, and with removeIf; and do the same with a Python list in a for loop.

P13. Buffering and character encodings

Write Io.java: write 200,000 short lines with an unbuffered FileOutputStream and with a BufferedWriter, timing both; then write Crème brûlée, ₹120 as UTF-8 and read it back as UTF-8 and as ISO-8859-1. If you're on Linux, run the program under strace -c -f -e trace=write and count the system calls. If the UTF-8 text prints as ?, set LANG=C.UTF-8 and explain why.

P14. Strings at scale, and data that changes in transit

  1. Time building a 10,000- and a 40,000-character string with += in a loop versus StringBuilder.
  2. In Node.js, JSON.parse('{"orderId": 9007199254740993}') and print the ID and Number.isSafeInteger.
  3. In Python, define @dataclass OrderV1(id: str, paise: int) and load {"id": "o1", "paise": 14900, "currency": "AED"} strictly (OrderV1(**d)) and tolerantly (only known fields). Explain what each reader does wrong.

P15. Let the computer find your bug

Install the property-based testing library Hypothesis (pip install hypothesis pytest). Here's a bill splitter:

Python
def split_bill(total_paise, people):
    share = round(total_paise / people)
    return [share] * people

Write a property test: for any total from 0 to 10,000,000 and any number of people from 1 to 12, the shares add up to the total. Run it with pytest and read the minimal failing example Hypothesis reports. Then fix the function and make the property pass. Finally, state two more properties a correct splitter must satisfy.

P16. Same task, three paradigms

Compute revenue per kitchen (excluding cancelled orders) from five orders three ways: an imperative loop with a TreeMap, a Java stream with groupingBy and summingLong, and SQL in an in-memory SQLite database (from Python's sqlite3). Check all three agree. Then answer: which version would you parallelise, which would you put in front of 50 million rows, and which is easiest to change when "cancelled" becomes "cancelled or refunded"?

P17. Scope, initialisation and the cost of the wrong collection

  1. Write the three snippets from T3 (uninitialised local, shadowed field, Python global assignment) and record the exact messages.
  2. Fill an ArrayList and a HashSet with 100,000 integers, then time 2,000 contains lookups in each.

P18. Native code: layout and undefined behaviour

  1. In C, print sizeof and the offset of price for struct Bad { char veg; int price; char spicy; } and struct Good { int price; char veg; char spicy; }.
  2. Compile this loop with -O0, -O2, -O2 -fwrapv and -O2 -fsanitize=undefined, and run each (with timeout 3 in front):
C
int count = 0;
for (int i = INT_MAX - 2; i > 0; i++) count++;
printf("loop ran %d times\n", count);

Explain why the same source behaves differently, and why this matters to Java developers.

Cumulative projects (chapters so far: 01–02)

These combine chapter 02 with everything in chapter 01: standard streams, redirection, exit codes, files and paths, bytes and encodings, memory vs storage, and reading errors.

C1. An order ledger on the command line

Write Ledger.java. It reads CSV lines id,kitchen,paise,method from standard input (UTF-8; skip blank lines and lines starting with #), and prints total revenue per kitchen, sorted by name, formatted as rupees (₹149.00). An optional argument restricts the output to one kitchen. Requirements:

  • Parsing returns a sealed result (Ok(Order) or Bad(line, reason)), handled with a pattern switch; no exceptions for bad input.
  • Order is an immutable record that rejects negative amounts in its constructor; payment method is an enum parsed case-insensitively and locale-independently.
  • Totals use long paise and overflow-checked addition.
  • Bad lines go to standard error with line numbers; exit codes: 0 all good, 2 some lines skipped, 1 nothing valid.

Test it with a file that includes: an unknown method (wallet), an amount 1.5e3, a line with a missing field, a negative amount, and mixed-case methods; and test the filter argument and the "no valid orders" case.

Combines: streams, redirection and exit codes (ch 01); records, enums, sealed types, pattern matching, error models, integer arithmetic, locale-independent case conversion, encodings (ch 02).

C2. A disk-usage tool, recursive and iterative

Write Du.java that totals the sizes of all regular files under a folder given as an argument (default: the current folder), in two ways: a recursive method and an iterative one with an explicit ArrayDeque stack. Both must: not follow symbolic links (create a loop with ln -s .. tree/a/b/loop to test), report unreadable entries to standard error and keep going, use long for sizes, and exit 1 if anything was unreadable. Compare your total with du -sb --apparent-size and explain any difference. Finally, argue which version you'd ship.

Combines: paths, files, folders, permissions and exit codes (ch 01); recursion vs iteration, the stack, error handling, long arithmetic (ch 02); and two concepts from the gaps sections (symbolic links, permissions).

C3. Port a Python script to Java without changing its behaviour

This Python function computes a delivery slot index and a loyalty discount:

Python
def slot_and_discount(minutes_from_midnight, orders_this_month, total_paise):
    slot = (minutes_from_midnight - 30) // 60 % 24          # slots start at 00:30
    tier = orders_this_month // 10
    discount = round(total_paise * min(tier, 3) * 0.05)
    return slot, discount

Port it to Java so that it gives identical results for every input, including minutes_from_midnight = 0, total_paise values like 50 and 10,000,000,000, and orders_this_month = 25. List every semantic difference you had to handle, and write a small test that compares the two implementations on many generated inputs (call Python from Java with a process, or generate test cases from Python into a file that Java reads).

Combines: processes, files and streams (ch 01); integer and floor division, remainder signs, overflow, floating point, rounding modes, conversions and testing (ch 02).

C4. A tested allocation library, with assertions that actually run

Write a Java class Money with static long[] allocate(long totalPaise, int[] ratios) that splits an amount in proportion to ratios (for example a ₹999.99 refund across kitchens in ratio 1:2:3) so that the parts always add up exactly, and no part differs from its exact share by a paisa or more. Requirements:

  • Validate inputs (no negative total, at least one ratio, no negative ratios, not all zero) with clear exceptions.
  • Use assert to check the invariant "parts sum to total" at the end of the method, and show what happens when you run with and without -ea.
  • Write a main that tests 10,000 random cases (fixed seed) against the two properties and exits non-zero on the first failure, printing the failing input.
  • Produce a deliberately buggy version (round each share independently) and show that your test catches it.

Combines: exit codes, standard error and reading failures (ch 01); integer division and remainders, exceptions vs invariants, immutability of results, property-based testing, debugging (ch 02); and the "assertions are disabled by default" gap below.

What the chapter leaves out

Chapter 02 covers a great deal across six languages. From a senior engineer's perspective, these are the important ideas it skips or only touches. The senior exercises build on them. Tick each one when you could explain it to a colleague.

The equals and hashCode contract

The chapter mentions hashCode once. In practice it's one of the most common sources of subtle Java bugs. The contract: if a.equals(b), then a.hashCode() == b.hashCode(); equals must be reflexive, symmetric and transitive; and both must stay stable while the object is in a hash-based collection. Break the first rule and HashSet keeps duplicates (P9). Break the last (mutate a key's fields after inserting it) and the entry becomes unreachable: the lab put a key in a HashMap, changed its field, and then neither the original nor the new value could find it, though size() was still 1 (S1). Rules: use records or immutable keys; generate both methods together; never mutate objects used as keys or set elements; for class hierarchies, be careful about equals across subclasses (it's hard to keep symmetric).

Memory visibility and the Java Memory Model

The chapter's concurrency section describes models (threads and locks, message passing, async). What it doesn't cover is that, without synchronisation, one thread's writes may never become visible to another: CPUs cache values in registers and caches, and compilers reorder instructions. A boolean running flag set by one thread can be read as true forever by another. Java's memory model defines happens-before relationships: an unlock happens-before a later lock of the same monitor, a volatile write happens-before a later read of it, Thread.start and join create edges, and final fields are safely published after construction. Atomic classes (AtomicInteger, LongAdder) combine visibility with atomic read-modify-write. The lab's lost updates (S4) are the atomicity half of the problem; visibility is the other half, and it's harder to observe because it depends on the machine and the JIT. Deeper: Volume 1 chapter 8 and Volume 5.

Semantic versioning and compatibility

The chapter introduces dependencies and build tools but not the rules that make ecosystems work. Semantic versioning (MAJOR.MINOR.PATCH) promises: patch = bug fixes, minor = backwards-compatible additions, major = breaking changes. "Compatible" has levels (T16): source, binary, and behavioural (same results). Hyrum's law adds the uncomfortable truth: with enough users, every observable behaviour of your API, including bugs, error message text and ordering, will be depended on by somebody. So library authors deprecate before removing, keep behaviour stable, and use tools like japicmp or revapi to detect binary-incompatible changes in CI.

Test quality beyond "it has tests"

The chapter introduces unit tests and mentions property-based testing. Senior-level testing adds:

  • Coverage measures what ran, not what was checked. A test with no assertions gives 100% line coverage. Mutation testing (PIT for Java) changes your code in small ways (< to <=, + to -) and checks whether any test fails; surviving mutants show untested behaviour.
  • Test doubles have different jobs: stubs return canned answers, fakes are working lightweight implementations (an in-memory repository), mocks verify interactions. Over-mocking produces tests that pass while the real integration is broken; prefer fakes and real components (Testcontainers for databases) where practical.
  • Flaky tests (pass and fail on the same code) usually come from time, randomness, ordering, shared state or concurrency. Inject clocks and random seeds, isolate state, and fix or quarantine flaky tests quickly: a test suite people don't trust is ignored.
  • The test pyramid: many fast unit tests, fewer integration tests, very few end-to-end tests.

Assertions are off by default in Java

Java's assert statement is disabled unless the JVM runs with -ea: the lab's assert 1 > 2 passed silently without it and threw AssertionError with it. So assert must never be used to validate inputs or protect security checks, only to document and check internal invariants during testing. Python has a similar trap: python -O removes assert statements. Use explicit checks (Objects.requireNonNull, if (…) throw new IllegalArgumentException) for anything that must always hold.

Locale-sensitive operations in ordinary code

Several everyday string operations silently depend on the machine's default locale: "title".toUpperCase() on a Turkish-locale machine gives TİTLE (dotted capital I), so an enum lookup Method.valueOf(s.toUpperCase()) fails there; String.format("%.2f", 1234.5) gives 1234,50 in a German locale, which breaks any machine-readable output (CSV, JSON, SQL). The lab reproduced both. Rule: for machine-readable text, always pass Locale.ROOT; for human-readable text, pass the user's locale explicitly (Volume 23 covers this fully).

Algorithmic cost of everyday operations

The chapter's focus is semantics, but choosing the wrong operation is the most common performance bug in ordinary code: list.contains in a loop (P17: 570× slower than a HashSet at 100,000 items), string += in a loop (P14: quadratic), list.remove(0) on an ArrayList (shifts every element), and reading a database row per item (the N+1 query problem). A senior habit is to know the cost of the standard library's operations and to ask "how many times does this run, and on how much data?" for every loop. Deeper: chapters 3 and 4.

Logging and errors together

The chapter covers error models but not how errors are observed in running systems. Common practices: log an error once, where it's handled, not at every layer it passes through ("log and rethrow" produces the same stack trace five times); include identifiers and context (order ID, request ID), not just the message; use levels deliberately (ERROR means someone should act); use structured logs (key-value or JSON) that tools can search; never log secrets or full card numbers. Keep the cause when wrapping exceptions (chapter 01's S10). Deeper: Volume 7.

Static analysis as part of the language

Modern Java and Python development relies on tools that catch whole classes of bugs from this chapter before tests run: Error Prone and SpotBugs (boxed ==, broken equals, int-overflow-to-long, ignored return values), NullAway and JSpecify (null safety), Checkstyle and formatters (consistency), and for Python ruff, mypy and pyright (mutable defaults, undefined names, type errors). They're cheap to adopt in CI and catch exactly the bugs code review misses because they look normal.

Resources other than memory

The chapter discusses memory management models (manual, garbage collection, ownership) in depth. But garbage collection manages only memory: file handles, sockets, database connections, locks and threads are finite too, and the GC won't close them in time (finalizers are deprecated, and Cleaner is a last resort). Leaking connections exhausts a pool and stalls a service while plenty of memory is free. Always tie resource lifetime to scope (try-with-resources, with, defer, RAII; T9), and monitor pool usage in production.

Senior exercises

S1. The order that vanished from the cache

An in-memory cache is a HashMap<OrderKey, Order>, where OrderKey has a mutable code field and correct equals/hashCode based on it. After a "normalisation" step changes some keys' codes in place (trimming spaces), those orders can't be found, though the map's size hasn't changed and memory keeps growing. Reproduce it with a key whose code is changed after insertion; try get with both the old and the new code; print size(). Explain the mechanism inside HashMap, why memory grows, and what rules (and tools) you'd put in place for the team.

S2. Design the error model for a payments client library

Your team owns the Java client library that 30 other services use to call the payments gateway. Design its error model: the exception or result types it exposes, how callers tell retryable from non-retryable failures, what information each error carries, how it handles timeouts and retries internally (if at all), and what it guarantees about idempotency. Then write the one-page decision record you'd circulate (Volume 24's chapter 04 format: context, decision, consequences).

S3. Numbers that change between services

A Java order service, a Python analytics service and a TypeScript web app share order data as JSON. In one month you saw: (1) the web app showing the wrong order after a customer clicked a link; (2) analytics revenue totals differing from finance by a few paise per thousand orders; (3) a Python report showing a refund of -0.0. Explain the probable cause of each from this chapter's material, and write the cross-service data contract (types and formats) you'd propose.

S4. Lost updates

Write Race.java: four threads each increment a shared static int one million times, and also an AtomicInteger. Run it twice. Explain why the int total is wrong and different each run, then fix it four ways (synchronized, AtomicInteger, LongAdder, thread confinement with a final merge) and discuss which you'd use for (a) a request counter updated by 200 threads and read once a minute, (b) an account balance, (c) a per-request computation.

S5. Undefined behaviour in a dependency

Your Java service uses a native image-processing library through JNI. Crash reports show occasional JVM crashes (hs_err_pid*.log files) in the native code, only in production builds and only for some uploaded images. Using P18's results, explain how undefined behaviour could produce a crash that appears only with optimisation and only on some inputs. Then write the investigation and mitigation plan: how to reproduce, which tools to use, and how to protect the service while the library is fixed.

S6. Untrusted depth

Your API accepts JSON documents describing nested menus (categories containing categories). A recursive Java function converts them to domain objects. Write a threat model paragraph explaining the denial-of-service risk, using P7's measurements. Then write the iterative version of a function that computes the nesting depth and total item count of a nested structure using an explicit stack, add a configurable depth limit with a clear error, and say where else in a typical backend the same risk appears.

S7. A public API that leaks its insides

Review this class, which your team publishes in a shared library used by eight services:

Java
public class Menu {
    private final List<Dish> dishes;
    private final Map<String, Integer> prices;
    public Menu(List<Dish> dishes, Map<String, Integer> prices) { this.dishes = dishes; this.prices = prices; }
    public List<Dish> getDishes() { return dishes; }
    public Map<String, Integer> getPrices() { return prices; }
    public int priceOf(String dish) { return prices.get(dish); }
}

Find every way a caller can break this object's integrity or crash on it, rewrite it, and write the review comment you'd leave, prioritising the issues.

S8. Evolve a message schema without breaking anyone

TiffinBox's OrderPlaced event (JSON on a message queue) has {"id", "kitchen", "paise"}. Dubai launch needs AED amounts. Eight consumers read the event; you can't deploy them all at once. Design the change: the new schema, the order of deployments, what old and new consumers do during the transition, how you detect consumers that haven't migrated, and when the old field can be removed. Explain why "just add a currency field" (P14) is wrong.

S9. A dependency upgrade that breaks at run time

After upgrading a logging library from 2.17 to 2.20, your service starts fine but fails on one rarely used endpoint with java.lang.NoSuchMethodError: 'void com.example.json.Writer.writeRaw(java.lang.String)'. The failing class is in a different library, a metrics client, which you didn't upgrade. Explain the mechanism (T16), how to find which versions are on the classpath and why, how to fix it now, and what process would have caught it before production.

S10. Review a junior engineer's pull request

A new team member submits this method for the refunds service. Find every problem related to this chapter, rank them, and write the review: blocking issues, suggestions, one piece of genuine praise, and an offer to pair. Then write the corrected method.

Java
public static double refundAmount(String status, Integer paidPaise, int daysSinceOrder, List<String> items) {
    if (status == "CANCELLED") {
        return paidPaise / 100;
    }
    double refund = 0;
    try {
        for (String item : items) {
            if (item.startsWith("damaged:")) { refund += paidPaise / items.size() / 100; items.remove(item); }
        }
        if (daysSinceOrder > 7) refund = refund * 0.5;
    } catch (Exception e) { }
    return refund;
}