Workbench / Volume 3 Exercises: The Backend
V3·33
Language Foundations
Exercises for Volume 3, chapter 33: syntax families and program structure; primitive types, integer overflow and floating point; reference and value types; operators and equality; control flow; arrays and strings; methods and parameter passing; classes, interfaces, packages, modules and visibility; enums and records; error-handling models; and annotations, with Java as the main language and Kotlin, Go, Rust and Python for comparison. 10 theory questions, 10 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
Volume 3 is the backend volume, and its exercises follow the same four sets and the same locking as Volumes 1 and 2. Most exercises are in Java, with Go 1.24, Rust 1.97 and Python 3 for comparison. The measured outputs come from JDK 21 (java -Dstdout.encoding=UTF-8 F.java), and every quoted output is real. Five of them catch experienced developers:
- P4:
new BigDecimal("2.0").equals(new BigDecimal("2.00"))is false, so aHashSetkeeps both values. - P6: Java's
NumberFormatforen-INprinted ₹1,234,567.50, not the Indian ₹12,34,567.50 that JavaScript'sIntlgives. - P6:
"title".toUpperCase()in a Turkish locale gave TİTLE. - P7: a record holding a mutable list, mutated after it went into a
HashSet, madeset.contains(t)return false. - P8: a
returninfinallysilently replaced thetryblock's return value.
The chapter's lab measured silent int overflow (Integer.MAX_VALUE + 1 = -2147483648), the Integer cache (128 == 128: false), string += in a loop (992.6 ms vs 0.36 ms with StringBuilder), boxing (int[] 5.7 ms vs List<Integer> 18.7 ms) and exception cost (67.1 ms vs 1.7 ms without stack traces). The exercises build on those.
TiffinBox's order service is the running example. Money is in paise throughout, as in Volume 2.
Coverage map.
| Chapter component | Exercises |
|---|---|
| syntax families, program structure, a minimal program per language | T1, P1 |
| primitive types; integer overflow | T2, P2 |
| floating point; BigDecimal for money | T3, P3, P4 |
| reference types and value types; boxing | T4, P5 |
| operators and equality | T4, P4 |
| control flow; switch and pattern matching | T5, P9 |
| arrays | T6, P5 |
| strings, Unicode, locales | T6, P6 |
| methods and parameter passing | T7, P5 |
| classes; interfaces; packages, modules, visibility | T7, T8 |
| enums | T9, P9 |
| records and data classes | T9, P7 |
| error-handling models | T10, P8, P10 |
| annotations | T8, P10 |
Theory
T1. Syntax families and how Java runs your code
- Group Java, Kotlin, C#, Go, Rust, Python and TypeScript into syntax families (C-style braces, indentation-based, expression-oriented), and say what each family makes easy or error-prone (missing braces in
if, significant whitespace, statements vs expressions). - Explain how Java runs code:
.java→javac→ bytecode in.classfiles → the JVM loads, verifies, interprets, then JIT-compiles hot methods (C1, C2). What doesjava F.java(the single-file source launcher) do, and why did this chapter's helpful-NPE message say"<local16>"instead of a variable name? - Compare a minimal "print the order total" program in Java, Kotlin, Go and Rust: where does
mainlive, how are modules/packages declared, what does each language require you to declare (types, exceptions, mutability), and what does that tell you about each language's priorities?
T2. Primitive types and integer overflow
- List Java's eight primitives with sizes and ranges (
byte,short,int,long,float,double,char,boolean) and say which you'd use for: an order count, an order total in paise, a price in paise across a year's revenue, a quantity limit of 5, a GST rate, a flag. - The lab:
Integer.MAX_VALUE + 1wrapped to-2147483648,(int) 2,500,000,000Lgave-1794967296, andMath.addExactthrew. P2 compared languages: Go wrapped (MaxInt32 + 1 = -2147483648); Rust's debug build panicked ("attempt to add with overflow") and its release build wrapped; Rust'schecked_addreturnedNone,saturating_add2147483647; Python's integers grew to2147483648. What should a backend do about overflow in money, counters and ids? - P2's other integer surprises:
-7 / 2 = -3,-7 % 3 = -1(butMath.floorMod(-7, 3) = 2, and Python's-7 % 3 = 2),Math.abs(Integer.MIN_VALUE) = -2147483648,(byte) 200 = -56,'a' + 1 = 98. Explain each and give a real bug it causes.
T3. Floating point and money
- P3:
0.1 + 0.2 = 0.30000000000000004,0.1 * 3 == 0.3is false,NaN == NaNis false (butDouble.valueOf(NaN).equals(NaN)is true),1.0/0 = Infinity,0.0 == -0.0is true whileDouble.compare(0.0, -0.0) = 1. Explain IEEE 754 binary floating point and each result. - P3:
new BigDecimal(0.1)printed0.1000000000000000055511151231257827021181583404541015625whileBigDecimal.valueOf(0.1)printed0.1;1/3without a rounding mode threwArithmeticException: Non-terminating decimal expansion; ₹100 split three ways at scale 2 gave 33.33;0.125rounded to 0.12 withHALF_EVENand 0.13 withHALF_UP. How should TiffinBox represent and round money in Java? - When is
doublefine (ratings, distances, ML features, statistics) and when not (money, quantities with exact rules, ids)?
T4. Reference types, value types, boxing and equality
- Explain primitives vs references in Java (stack/locals vs heap objects,
null, identity), how C# structs, Go structs, Rust values and Kotlin's value classes differ, and what Project Valhalla's value classes will change. - The lab's Integer cache (
127 == 127true,128 == 128false) and P5's unboxing results: unboxingnullthrew an NPE;int q = map.get("vada")for a missing key threw an NPE;true ? (Integer) null : 0threw an NPE;true ? 1 : 2.0printed1.0. Explain autoboxing, the cache, and the ternary's numeric promotion rules. - State Java's equality rules:
==for primitives (value) and references (identity),equalsfor logical equality (and its contract withhashCode),compareTofor ordering (P4:BigDecimal2.0 vs 2.00 equals false, compareTo 0; HashSet kept 2, TreeSet 1). Compare with Go (==on comparable structs: P2 true), Rust (PartialEqderived) and Python (==vsis: P2 showed256 is 256True and257 is 257False, Python's own small-int cache).
T5. Control flow: switch, pattern matching and loops
- Compare Java's old
switchstatement (fall-through,break) with switch expressions (->,yield, exhaustiveness), andif/elsechains. Rewrite a fee calculation using a switch expression on aDeliveryZoneenum. - Explain pattern matching in Java 21:
instanceofpatterns (if (p instanceof Upi u)), record patterns (case Card(String last4)),switchon sealed hierarchies with exhaustiveness checking (P9'sdescribe(Payment)returned "UPI asha@okicici" and "card ••4242" with nodefault), guards (case Upi u when u.vpa().endsWith("@okicici")), andnullhandling in switch. - Loops and iteration: classic
for, enhancedfor,while, iterators, streams (chapter 37), labelledbreak. What happens when you modify aListinside an enhancedfor(ConcurrentModificationException), and how do you remove items safely (removeIf, iteratorremove)?
T6. Arrays and strings
- Arrays in Java: fixed length, covariance (
Object[] a = new String[1]; a[0] = 1;→ArrayStoreException), default values,Arrays.equals/hashCode/toStringvs the object methods (P7: a record with anint[]component wasn't equal to an identical one), multi-dimensional arrays, and when to preferList. - Strings: immutability, the string pool and interning (P6: a literal
==a compile-time constant"do" + "sa"was true,== new Stringfalse,==a runtime concatenation false,.intern()true),+in loops (the lab: 992.6 ms vs 0.36 ms), text blocks,String.formatvs formatted,stripvstrim,isBlank. - Unicode and locales: P6 measured
"₹180".length()4,"🍛".length()2 (one code point, two UTF-16 chars, andsubstring(0, 1)returned a lone surrogate), Telugu"దోస"length 3 but 9 UTF-8 bytes (Go'slenalso 9, Rust 9 bytes and 3 chars, Python 3);"title".toUpperCase(tr)=TİTLE; and Java'sen-INandhi-INcurrency formats printed₹1,234,567.50(Western grouping). Explain each and the rules for backend code.
T7. Methods, parameter passing and classes
- P5: after
swap(a, b)(reassigning parameters) andmutate(a)(callingappend),awas"dosa + chutney"andb"idli". Explain "Java is always pass-by-value; for objects, the value is a reference", and compare with C++ references, C#ref, Go pointers and Rust&mut. - Classes: fields, constructors,
this, static vs instance members, initialisation order (static initialisers, instance initialisers, constructor chains),finalfields and safe publication,toString/equals/hashCode, and nested/inner/local/anonymous classes. Which are everyday tools and which are traps (inner classes holding outer references, overridable methods called from constructors)? - Method design: overloading vs varargs pitfalls, defensive copies, returning
Optionalvsnull, immutability by default, and keeping methods small and side-effect-free where possible.
T8. Interfaces, packages, modules, visibility and annotations
- Interfaces in Java: abstract methods,
defaultandstaticmethods,privateinterface methods, functional interfaces and lambdas (the chapter's "interfaces and lambdas" section), sealed interfaces. When do you use an interface vs an abstract class vs a sealed hierarchy? - Visibility:
public,protected, package-private,private; packages as namespaces and encapsulation boundaries; JPMS modules (module-info.javawithexportsandrequires) and strong encapsulation of JDK internals (--add-openserrors). How do these compare with Go's capitalisation rule and Rust'spub/pub(crate)? - P10's annotations: a
@Retention(RUNTIME)@Audited("orders")was visible via reflection; a@Retention(CLASS)@BuildOnlywasn't. Explain retention policies, targets, how frameworks use annotations (Spring, JPA, Jackson, Bean Validation: chapters 46, 49), annotation processors (Lombok, MapStruct, Dagger), and the cost of reflection-heavy frameworks.
T9. Enums and records
- Enums: type-safe constants with fields, methods and constructors;
values(),valueOf(P9:Status.valueOf("cooking")threwNo enum constant F.Status.cooking),ordinal()(P9: READY = 2),EnumMap/EnumSet, and switch exhaustiveness. What are the traps with persistingordinal()or names, and parsing external input? - Records: transparent data carriers with components, canonical/compact constructors (P7: a compact constructor rejected a negative price), auto-generated
equals/hashCode/toString(P7: equal by value,Line[dish=Idli, paise=4000]), immutability (shallow), and what records can't do (extend classes, have instance fields beyond components). P7 found that a record holding a mutableList, mutated after insertion into aHashSet, madecontainsreturn false. Explain and fix. - Compare with Kotlin data classes (
copy, destructuring), C# records (withexpressions), Go structs and Rust structs with derived traits. When should a domain type be a record, an enum, a sealed interface of records, or a regular class?
T10. Error-handling models
- Compare error models: Java checked and unchecked exceptions; Kotlin (no checked exceptions,
Result/runCatching); Go expliciterrorreturns with wrapping (P2:find 3: dish not found,errors.Is(err, ErrNotFound)true) andpanic/recover(P2: assigning to a nil map panicked and was recovered); Rust'sResult<T, E>with?(P2:Ok(36000),Err(NotFound(3))) andpanic!. What does each optimise for? - P8: try-with-resources closed resources in reverse order and attached both close failures as suppressed exceptions (
primary 'body failed', suppressed [close failed: file, close failed: db]), and areturn 2infinallyoverrodereturn 1intry. Explain both, and other exception pitfalls (catchingException/Throwable, swallowing, losing the cause, exceptions for control flow: the lab's 67.1 ms vs 1.7 ms). - Design TiffinBox's error strategy in Java: domain exceptions vs result types, where to translate (repository → service → HTTP: chapter 44's problem details), what to log, and how to make errors testable.
Programming exercises
P1. One program in four languages
Write "compute an order total in paise from three lines, apply a 10% coupon with half-up rounding, add 5% GST, print it formatted" in Java, Kotlin (or Go), Go and Rust. Compare: lines of code, how each handles integer types and rounding, how errors (an unknown dish id) are reported, and how long a cold run takes. Keep the outputs identical.
P2. Overflow, division and casts across languages
Reproduce in Java: Integer.MAX_VALUE + 1, Math.addExact, (int) 2_500_000_000L, -7 / 2, -7 % 3, Math.floorMod(-7, 3), Math.abs(Integer.MIN_VALUE), (byte) 200, 'a' + 1. Then the same overflow in Go, Rust (debug and release, plus checked_add, wrapping_add, saturating_add) and Python. Finally, fix a sharding function Math.abs(key.hashCode()) % shards and a total computation that can overflow.
P3. Floating point traps and BigDecimal
Print 0.1 + 0.2, 0.1 * 3 == 0.3, NaN == NaN, Double.valueOf(NaN).equals(NaN), 1.0/0, 0.0 == -0.0 and Double.compare(0.0, -0.0); then new BigDecimal(0.1) vs BigDecimal.valueOf(0.1), 1/3 without and with a rounding mode, a ₹100 three-way split, and 0.125 with HALF_EVEN vs HALF_UP. Then write splitBill(BigDecimal total, int ways) that distributes the remainder so the parts add up exactly.
P4. Equality: ==, equals, hashCode and compareTo
Demonstrate: the Integer cache (127 == 127, 128 == 128), String == vs equals in four cases (literal, compile-time constant, new String, runtime concatenation, intern()), BigDecimal("2.0") vs "2.00" in equals, compareTo, a HashSet and a TreeSet. Then write a Money value type (record) that's safe as a map key and consistent between hash and sorted collections.
P5. References, boxing, arrays and parameter passing
Show: swap(a, b) not swapping and mutate(a) mutating; unboxing null (a field, map.get of a missing key, a ternary with (Integer) null); true ? 1 : 2.0 printing 1.0; array covariance throwing ArrayStoreException; and the lab's boxing cost (int[] vs List<Integer>). Then refactor a method void applyCoupon(Cart cart, String code, Integer discountOut) that tries to "return" a discount through a parameter.
P6. Strings, Unicode and locales
Measure length(), code point counts and UTF-8 byte lengths for "₹180", "🍛" and Telugu "దోస"; show that substring(0, 1) of the emoji is a lone surrogate; uppercase "title" in Turkish and Locale.ROOT; and format ₹12,34,567.50 with NumberFormat for en-IN and hi-IN and with String.format. Compare with Go, Rust and Python string lengths. Then write truncateForSms(String s, int maxCodePoints) that never splits a code point (or grapheme) and a formatter that prints Indian grouping.
P7. Records: validation, equality and immutability
Write record Line(String dish, long paise) with a compact constructor that rejects negative prices and blank names; show value equality and toString; then reproduce the two record traps: a List component mutated after the record is put in a HashSet (contains false), and an int[] component making equal-looking records unequal. Fix both, and add a with-style copy method.
P8. Exceptions: resources, finally and cost
Show try-with-resources with two resources whose close() throws while the body throws (order and suppressed exceptions), a return in finally overriding the try's return, and the lab's cost of stack traces. Then refactor an import that parses 100,000 CSV quantities with Integer.parseInt inside try/catch to a version that validates first, and measure.
P9. Enums, sealed types and exhaustive switches
Model order status as an enum with allowed transitions, payment as a sealed interface of records (Upi, Card, Cash), and write switch expressions without default (fee by zone, description by payment). Show valueOf failing on bad input, ordinal, EnumMap, and what the compiler says when you add Wallet to the sealed interface without handling it. Write a safe parser for external status strings.
P10. Annotations and a tiny framework
Define @Audited(String value) with RUNTIME retention and @BuildOnly with CLASS retention, apply both, and check visibility via reflection. Then build a 40-line "framework" that scans a list of service classes, finds @Audited methods, and wraps calls with audit logging using a dynamic proxy (java.lang.reflect.Proxy). Measure the call overhead of the proxy, and compare with doing it at compile time (an annotation processor or plain code).
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33)
C1. TiffinBox's money and order domain in Java
Implement the order domain as a small Java library: Money (P4), Quantity (1–5), Line (P7), Coupon rules returning results (P5), Status with transitions (P9), sealed Payment and OrderEvent types, GST and rounding rules matching Volume 2's frontend exactly (chapter 33's P2 table), Indian formatting (P6), and domain exceptions (T10). Write unit tests and property tests (jqwik) proving totals never overflow or go negative, and contract tests ensuring the Java totals equal the TypeScript ones for 10,000 random carts.
Combines: Volume 1's number representation and testing (ch 01, 06), Volume 2's money rules, schemas and testing (ch 16, 26, 33) and this chapter.
C2. Port a Go or Python service's error handling to Java (and back)
Take a small order-lookup service written in Go (errors as values with %w wrapping, errors.Is) and port it to Java twice: once with exceptions, once with sealed result types. Compare readability, testability, how context is preserved, and how errors map to HTTP status codes. Then port one function to Rust with Result and ?.
Combines: Volume 1's API and error-design discussions, Volume 2's HTTP status handling (ch 19's T1) and this chapter's error models.
C3. A Unicode- and locale-safe notification service
Build the SMS/WhatsApp notification text generator for orders in English, Hindi and Telugu: templates with placeholders, Indian rupee formatting (P6), truncation to the provider's limits measured correctly (GSM-7 vs UCS-2 SMS encoding: 160 vs 70 characters per segment), no split graphemes (P6), locale-independent casing for codes, and tests with real Telugu and Hindi strings and emoji. Measure segment counts for typical messages in each language.
Combines: Volume 1's encodings (UTF-8, UTF-16: ch 06), Volume 2's internationalisation concerns (ch 21's gaps) and this chapter's strings and locales.
What the chapter leaves out
Generics, collections and streams in the type system
Language foundations touch generics only lightly; Java's generics (type parameters, bounded types, wildcards and erasure), collections (List, Set, Map and their implementations) and streams have deep consequences for API design and performance. They're chapters 35–37: start with List<Money> instead of List raw types, and treat @SuppressWarnings("unchecked") as a code review flag.
Null safety beyond Optional
Java's type system doesn't track nullability, so NPEs remain common (P5). Approaches: Optional for return values, validation at boundaries (Objects.requireNonNull in constructors: P7), nullability annotations checked by tools (JSpecify's @Nullable/@NullMarked with NullAway or IntelliJ), and design that avoids nulls (empty collections, null objects). Kotlin's nullable types (String?) and Rust's Option<T> show what compiler-enforced null safety looks like; JSpecify is the Java ecosystem's convergence point.
Immutability and functional style
Records give shallow immutability; deep immutability needs immutable collections (List.copyOf, Guava's ImmutableList), avoiding setters, and copy-on-write updates (withPaise). Combined with lambdas, Optional and streams, this functional style reduces shared mutable state, which matters most once threads appear (chapter 38). Chapter 37 covers functional programming in Java.
Language evolution and preview features
Java ships every six months (LTS every two years: 17, 21, 25), with preview features that need --enable-preview before they're final (string templates were withdrawn after previews, compact source files and instance main finalised in 25, primitive types in patterns and value classes in progress). Read JEPs for what's coming, adopt finalised features gradually, and use --release N to compile for the runtime you deploy. Chapter 40 covers modern Java through JDK 27.
Tooling that catches language traps
Many of this chapter's traps are found automatically: javac -Xlint:all (finally, deprecation, unchecked), Error Prone (== on boxed types, Math.abs(hashCode()), mutable record components), SpotBugs, SonarQube rules, IntelliJ inspections, and formatting/linting with Spotless or Checkstyle. Turn them on in the build (chapter 43) so code review discusses design, not == on Integer.
Senior exercises
S1. Write the Java language guidelines for the backend team
Write the team's Java guidelines covering: numeric types for money and ids, BigDecimal rules, equality, strings and locales, records vs classes vs enums vs sealed types, null handling, exceptions vs results, immutability, visibility and packages, annotations and frameworks, and the static analysis that enforces them. Each rule must name the bug it prevents.
S2. Review a pull request for language-level bugs
A PR adds a settlement job: it sums payouts into an int in paise, computes commission as payout * 0.18 in double, groups kitchens with Math.abs(kitchenId.hashCode()) % 16, compares statuses with status == "READY" on strings from the database, stores Status.ordinal() in a column, uses a record Settlement(String kitchen, List<Order> orders) as a HashMap key while adding orders later, and catches Exception around the whole job with e.printStackTrace(). Write the review.
S3. Decide between Java, Kotlin and Go for a new backend service
TiffinBox needs a new "kitchen payouts" service. The team knows Java (Spring), some engineers like Kotlin, and the platform team writes Go. Decide using language-level criteria from this chapter (null safety, error models, money handling, immutability, concurrency model preview, tooling, hiring) plus operational ones (start-up time, memory, ecosystem for payments and databases). Write the decision memo.
S4. Teach Java's equality and number rules with five outputs
Prepare a 15-minute session for engineers joining from Python and JavaScript using five real outputs: 128 == 128 false (lab), 0.1 + 0.2 (P3), BigDecimal 2.0 vs 2.00 in HashSet vs TreeSet (P4), Math.abs(Integer.MIN_VALUE) (P2), and the mutated record key (P7). For each, relate it to what they know from Python or JavaScript and give the rule. End with five rules.
S5. Assess a codebase's language-level health
You've inherited a 200,000-line Java backend. Plan a one-week assessment of language-level risks: what to search for (patterns from this chapter), which tools to run (Error Prone, SpotBugs, Sonar, -Xlint), how to rank findings by risk (money paths first), and how to fix them incrementally without a big-bang refactor. Produce the report outline.