Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

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.

34 exercises · ~15 min to read
Updated Suggest a correction

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 a HashSet keeps both values.
  • P6: Java's NumberFormat for en-IN printed ₹1,234,567.50, not the Indian ₹12,34,567.50 that JavaScript's Intl gives.
  • P6: "title".toUpperCase() in a Turkish locale gave TİTLE.
  • P7: a record holding a mutable list, mutated after it went into a HashSet, made set.contains(t) return false.
  • P8: a return in finally silently replaced the try block'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

  1. 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).
  2. Explain how Java runs code: .java → javac → bytecode in .class files → the JVM loads, verifies, interprets, then JIT-compiles hot methods (C1, C2). What does java F.java (the single-file source launcher) do, and why did this chapter's helpful-NPE message say "<local16>" instead of a variable name?
  3. Compare a minimal "print the order total" program in Java, Kotlin, Go and Rust: where does main live, 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

  1. 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.
  2. The lab: Integer.MAX_VALUE + 1 wrapped to -2147483648, (int) 2,500,000,000L gave -1794967296, and Math.addExact threw. P2 compared languages: Go wrapped (MaxInt32 + 1 = -2147483648); Rust's debug build panicked ("attempt to add with overflow") and its release build wrapped; Rust's checked_add returned None, saturating_add 2147483647; Python's integers grew to 2147483648. What should a backend do about overflow in money, counters and ids?
  3. P2's other integer surprises: -7 / 2 = -3, -7 % 3 = -1 (but Math.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

  1. P3: 0.1 + 0.2 = 0.30000000000000004, 0.1 * 3 == 0.3 is false, NaN == NaN is false (but Double.valueOf(NaN).equals(NaN) is true), 1.0/0 = Infinity, 0.0 == -0.0 is true while Double.compare(0.0, -0.0) = 1. Explain IEEE 754 binary floating point and each result.
  2. P3: new BigDecimal(0.1) printed 0.1000000000000000055511151231257827021181583404541015625 while BigDecimal.valueOf(0.1) printed 0.1; 1/3 without a rounding mode threw ArithmeticException: Non-terminating decimal expansion; ₹100 split three ways at scale 2 gave 33.33; 0.125 rounded to 0.12 with HALF_EVEN and 0.13 with HALF_UP. How should TiffinBox represent and round money in Java?
  3. When is double fine (ratings, distances, ML features, statistics) and when not (money, quantities with exact rules, ids)?

T4. Reference types, value types, boxing and equality

  1. 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.
  2. The lab's Integer cache (127 == 127 true, 128 == 128 false) and P5's unboxing results: unboxing null threw an NPE; int q = map.get("vada") for a missing key threw an NPE; true ? (Integer) null : 0 threw an NPE; true ? 1 : 2.0 printed 1.0. Explain autoboxing, the cache, and the ternary's numeric promotion rules.
  3. State Java's equality rules: == for primitives (value) and references (identity), equals for logical equality (and its contract with hashCode), compareTo for ordering (P4: BigDecimal 2.0 vs 2.00 equals false, compareTo 0; HashSet kept 2, TreeSet 1). Compare with Go (== on comparable structs: P2 true), Rust (PartialEq derived) and Python (== vs is: P2 showed 256 is 256 True and 257 is 257 False, Python's own small-int cache).

T5. Control flow: switch, pattern matching and loops

  1. Compare Java's old switch statement (fall-through, break) with switch expressions (->, yield, exhaustiveness), and if/else chains. Rewrite a fee calculation using a switch expression on a DeliveryZone enum.
  2. Explain pattern matching in Java 21: instanceof patterns (if (p instanceof Upi u)), record patterns (case Card(String last4)), switch on sealed hierarchies with exhaustiveness checking (P9's describe(Payment) returned "UPI asha@okicici" and "card ••4242" with no default), guards (case Upi u when u.vpa().endsWith("@okicici")), and null handling in switch.
  3. Loops and iteration: classic for, enhanced for, while, iterators, streams (chapter 37), labelled break. What happens when you modify a List inside an enhanced for (ConcurrentModificationException), and how do you remove items safely (removeIf, iterator remove)?

T6. Arrays and strings

  1. Arrays in Java: fixed length, covariance (Object[] a = new String[1]; a[0] = 1; → ArrayStoreException), default values, Arrays.equals/hashCode/toString vs the object methods (P7: a record with an int[] component wasn't equal to an identical one), multi-dimensional arrays, and when to prefer List.
  2. Strings: immutability, the string pool and interning (P6: a literal == a compile-time constant "do" + "sa" was true, == new String false, == a runtime concatenation false, .intern() true), + in loops (the lab: 992.6 ms vs 0.36 ms), text blocks, String.format vs formatted, strip vs trim, isBlank.
  3. Unicode and locales: P6 measured "₹180".length() 4, "🍛".length() 2 (one code point, two UTF-16 chars, and substring(0, 1) returned a lone surrogate), Telugu "దోస" length 3 but 9 UTF-8 bytes (Go's len also 9, Rust 9 bytes and 3 chars, Python 3); "title".toUpperCase(tr) = TİTLE; and Java's en-IN and hi-IN currency formats printed ₹1,234,567.50 (Western grouping). Explain each and the rules for backend code.

T7. Methods, parameter passing and classes

  1. P5: after swap(a, b) (reassigning parameters) and mutate(a) (calling append), a was "dosa + chutney" and b "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.
  2. Classes: fields, constructors, this, static vs instance members, initialisation order (static initialisers, instance initialisers, constructor chains), final fields 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)?
  3. Method design: overloading vs varargs pitfalls, defensive copies, returning Optional vs null, immutability by default, and keeping methods small and side-effect-free where possible.

T8. Interfaces, packages, modules, visibility and annotations

  1. Interfaces in Java: abstract methods, default and static methods, private interface 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?
  2. Visibility: public, protected, package-private, private; packages as namespaces and encapsulation boundaries; JPMS modules (module-info.java with exports and requires) and strong encapsulation of JDK internals (--add-opens errors). How do these compare with Go's capitalisation rule and Rust's pub/pub(crate)?
  3. P10's annotations: a @Retention(RUNTIME) @Audited("orders") was visible via reflection; a @Retention(CLASS) @BuildOnly wasn'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

  1. Enums: type-safe constants with fields, methods and constructors; values(), valueOf (P9: Status.valueOf("cooking") threw No enum constant F.Status.cooking), ordinal() (P9: READY = 2), EnumMap/EnumSet, and switch exhaustiveness. What are the traps with persisting ordinal() or names, and parsing external input?
  2. 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 mutable List, mutated after insertion into a HashSet, made contains return false. Explain and fix.
  3. Compare with Kotlin data classes (copy, destructuring), C# records (with expressions), 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

  1. Compare error models: Java checked and unchecked exceptions; Kotlin (no checked exceptions, Result/runCatching); Go explicit error returns with wrapping (P2: find 3: dish not found, errors.Is(err, ErrNotFound) true) and panic/recover (P2: assigning to a nil map panicked and was recovered); Rust's Result<T, E> with ? (P2: Ok(36000), Err(NotFound(3))) and panic!. What does each optimise for?
  2. 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 a return 2 in finally overrode return 1 in try. Explain both, and other exception pitfalls (catching Exception/Throwable, swallowing, losing the cause, exceptions for control flow: the lab's 67.1 ms vs 1.7 ms).
  3. 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.