BE·33
Language Foundations
The building blocks every backend language shares and where they differ: syntax families, primitive and reference types, overflow, operators and equality, control flow, arrays and strings, methods and parameter passing, classes and interfaces, packages and visibility, enums, records, error handling and annotations. Java is the reference point, compared throughout with Kotlin, C#, Go, Rust, C, C++, Zig, Python, TypeScript and the functional languages.
Start here: the Java language in one sitting
How Java runs your code
Java source code (.java files) is compiled by javac into bytecode (.class files): instructions for an imaginary machine, the Java Virtual Machine (JVM). The JVM then runs that bytecode on any operating system, first by interpreting it and then by compiling the busiest parts to native machine code while the program runs (just-in-time compilation, chapter 40). That's the meaning of Java's old slogan "write once, run anywhere", and it's why Kotlin, Scala and Clojure, which also compile to bytecode, can share the same libraries.
Every Java program is made of classes. Execution starts at a main method:
public class Hello {
public static void main(String[] args) {
System.out.println("Namaste from Java");
}
}
(Since JDK 25 a single-file program can be just void main() { IO.println("Namaste from Java"); }, which is handy for scripts and learning; real projects use classes in packages.)
Values: primitives and references
Java has eight primitive types that hold a value directly: int (32-bit whole numbers), long (64-bit), double (64-bit floating point), boolean, char (a UTF-16 code unit), plus byte, short and float. Everything else is an object, and a variable of an object type holds a reference to it (an arrow to where the object lives), not the object itself.
int cups = 3; long big = 9_000_000_000L; double ratio = 0.1 + 0.2; boolean open = true; char c = 'A';
System.out.println(cups + " " + big + " " + ratio + " " + open + " " + c + " " + (int) c);
3 9000000000 0.30000000000000004 true A 65
Variables are statically typed: the compiler knows every variable's type and rejects mismatches before the program runs. var dosa = new Dish(...) doesn't change that; it only asks the compiler to infer the type from the right-hand side.
Records, enums and the shape of your data
Most backend code moves data around: a dish, an order, a customer. Java's record declares an immutable data carrier in one line, with a constructor, accessors, equals, hashCode and toString generated for you. An enum is a fixed set of named values:
enum Category { BREAKFAST, LUNCH, SNACKS }
record Dish(String name, int pricePaise, Category category) {
Dish { // compact constructor: validate once, here
if (pricePaise <= 0) throw new IllegalArgumentException("price must be positive: " + pricePaise);
}
String rupees() { return "₹%d.%02d".formatted(pricePaise / 100, pricePaise % 100); }
}
Dish[name=Masala dosa, pricePaise=9000, category=BREAKFAST] costs ₹90.00
Validating in the constructor means an invalid Dish can never exist anywhere in the program, which is far safer than checking in every place that uses one. Records and enums are covered in depth in this chapter's full sections; ordinary classes (with mutable fields, private state and methods) are for objects with behaviour and identity, and chapter 34 is about designing them.
Strings: compare with equals
String is an object, so == compares references (is it the same object?), while equals compares contents:
String a = "dosa", b = new String("dosa");
System.out.println("a == b: " + (a == b) + " | a.equals(b): " + a.equals(b));
a == b: false | a.equals(b): true
Use equals for strings and all other objects. Strings are immutable: methods like toUpperCase() return a new string, which also makes them safe to share between threads.
Control flow
if, for, while and do/while work as in C and JavaScript. The modern switch expression returns a value, needs no break, and (for enums and sealed types) the compiler checks that every case is covered:
String meal = switch (dosa.category()) {
case BREAKFAST -> "morning";
case LUNCH -> "noon";
case SNACKS -> "evening";
};
The enhanced for loops over arrays and collections:
List<Dish> menu = new ArrayList<>(List.of(dosa, new Dish("Thali", 18000, Category.LUNCH), new Dish("Samosa", 2000, Category.SNACKS)));
int total = 0;
for (Dish d : menu) total += d.pricePaise();
System.out.println(menu.size() + " dishes, total ₹" + total / 100); // 3 dishes, total ₹290
Methods and how arguments are passed
Java passes every argument by value. For a primitive, the method gets a copy of the number; for an object, it gets a copy of the reference, so it can change the object the reference points to, but not the caller's variable:
static void bump(int[] arr, int n) { arr[0]++; n++; }
int[] counter = {0};
bump(counter, cups);
System.out.println("after bump: counter[0]=" + counter[0] + ", cups=" + cups); // counter[0]=1, cups=3
Interfaces and lambdas
An interface names a capability; any class (or lambda) can provide it. Code that depends on an interface works with every implementation, which is the foundation of testable, swappable backend code (and of Spring's dependency injection, chapter 46):
interface Discount { int apply(int paise); }
Discount tenPercent = p -> p * 90 / 100; // a lambda implementing the interface
System.out.println(new Dish("Thali", tenPercent.apply(18000), Category.LUNCH).rupees()); // ₹162.00
Exceptions
When something goes wrong, Java throws an exception object up the call stack until a catch handles it:
try {
new Dish("Free lunch", 0, Category.LUNCH);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage()); // rejected: price must be positive: 0
}
Java distinguishes checked exceptions (subclasses of Exception such as IOException, which the compiler forces you to catch or declare) from unchecked ones (subclasses of RuntimeException, for programming errors and invalid arguments). The full-depth section compares this with Go's error values, Rust's Result and C#'s and Kotlin's unchecked-only approach.
How deep to go in language foundations
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Read Java programs: types, classes, records, enums, interfaces, exceptions |
| L2 | Write correct, idiomatic Java and recognise the equivalent constructs in Kotlin, C#, Go, Rust and TypeScript |
| L3 | Explain primitive vs reference semantics, overflow and floating point, string handling, equality and hashing contracts, exception models |
| L4 | Diagnose overflow, boxing, equality, encoding and exception-handling bugs |
| L5 | Choose data modelling constructs (records, sealed hierarchies, value objects) and error-handling strategies for a codebase |
| L6 | Set language-level conventions and static analysis across teams; plan language-version upgrades |
Syntax and program structure
Syntax families
Most mainstream backend languages are in the C syntax family: braces for blocks, ; or newlines for statements, if (…), for, return, // comments. Java, C#, C++, Go, Rust, Zig, Kotlin, Scala, TypeScript and Swift all look familiar at a glance. The real differences are in semantics: what a variable holds, who owns memory, how errors flow, and what the compiler checks.
| Trait | Java | Go | Rust | C/C++ | Zig | Python |
|---|---|---|---|---|---|---|
| Entry point | static void main(String[]) in a class (or an instance void main(), final in JDK 25) |
func main() in package main |
fn main() |
int main(int, char**) |
pub fn main() !void |
module top level, if __name__ == "__main__" |
| Type declaration | int x = 1; (type first) |
var x int = 1 / x := 1 (type after) |
let x: i32 = 1; |
int x = 1; |
const x: i32 = 1; |
x: int = 1 (hint only) |
| Mutability default | mutable (final opts out) |
mutable | immutable (mut opts in) |
mutable (const opts out) |
const / var explicit |
mutable |
| Type inference | var (local only) |
:= |
everywhere local | auto (C++), none in C (C23 has auto) |
everywhere local | dynamic |
| Statement terminator | ; |
newline (auto-inserted ;) |
; (expression vs statement matters) |
; |
; |
newline |
| Compilation | bytecode + JIT | native AOT | native AOT (LLVM) | native AOT | native (LLVM, own backend) | bytecode, interpreted |
Two things deserve explicit attention because they change how you read code:
- Expressions versus statements. In Rust, Kotlin, Scala, Zig and the functional languages, almost everything is an expression that produces a value:
let x = if a { 1 } else { 2 };. Java historically separated them:ifis a statement, and the ternary?:is the expression form. Switch expressions (JDK 14) closed some of that gap. - Where types go. "Type after name" (
x: i32,x int) reads better with complex types and type inference. C's "declaration mirrors use" (int *(*fp)(char)) is why C function-pointer types are hard to read.
A minimal program in each language
// Java 25: compact source file with instance main (JEP 512, final in JDK 25)
void main() {
var names = List.of("ada", "linus", "grace");
for (var n : names) IO.println(n.toUpperCase());
}
// Classic form (still what you'll see in most codebases):
// public class App { public static void main(String[] args) { System.out.println("hi"); } }
fun main() {
val names = listOf("ada", "linus", "grace")
names.forEach { println(it.uppercase()) }
}
package main
import (
"fmt"
"strings"
)
func main() {
names := []string{"ada", "linus", "grace"}
for _, n := range names {
fmt.Println(strings.ToUpper(n))
}
}
fn main() {
let names = ["ada", "linus", "grace"];
for n in names {
println!("{}", n.to_uppercase());
}
}
const std = @import("std");
pub fn main() !void {
const names = [_][]const u8{ "ada", "linus", "grace" };
var buf: [64]u8 = undefined;
for (names) |n| {
const up = std.ascii.upperString(&buf, n); // no hidden allocation: you supply the buffer
std.debug.print("{s}\n", .{up});
}
}
#include <stdio.h>
#include <ctype.h>
int main(void) {
const char *names[] = {"ada", "linus", "grace"};
for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) {
for (const char *p = names[i]; *p; p++) putchar(toupper((unsigned char)*p));
putchar('\n');
}
return 0;
}
// C# top-level statements
var names = new[] { "ada", "linus", "grace" };
foreach (var n in names) Console.WriteLine(n.ToUpperInvariant());
names = ["ada", "linus", "grace"]
for n in names:
print(n.upper())
Notice what each one makes you think about. C makes you compute the array length and cast to unsigned char, because toupper on a negative char is undefined. Zig makes you provide the output buffer, because it never allocates behind your back. Rust and Go hide neither cost nor safety. Java and Python hide allocation entirely.
Types and values
Primitive types
Primitive (or scalar) types map directly to machine words: integers, floating point, booleans, characters. Their sizes and signedness differ across languages more than people expect:
| Concept | Java | C# | Go | Rust | Zig | C | Python |
|---|---|---|---|---|---|---|---|
| 8-bit | byte (signed!) |
sbyte/byte |
int8/uint8 (byte) |
i8/u8 |
i8/u8 |
int8_t (char signedness is implementation-defined) |
— |
| 32-bit | int |
int |
int32 |
i32 |
i32 |
int32_t (int is ≥ 16 bits) |
— |
| 64-bit | long |
long |
int64 |
i64 |
i64 |
int64_t |
— |
| Pointer-sized | — | nint |
int, uint, uintptr |
isize/usize |
isize/usize |
size_t, intptr_t |
— |
| Unsigned | none (except char); Integer.toUnsignedString, compareUnsigned |
yes | yes | yes | yes, plus arbitrary widths (u3, i47) |
yes | — |
| Arbitrary precision | BigInteger |
BigInteger |
math/big |
crates (num-bigint) |
std.math.big |
libraries (GMP) | int is arbitrary precision by default |
| Character | char = one UTF-16 code unit |
char = UTF-16 unit |
rune = int32 code point |
char = Unicode scalar value (4 bytes) |
u8/u21 |
char = a byte |
str of length 1 |
| Boolean | boolean |
bool |
bool |
bool |
bool |
_Bool / bool (C23 keyword) |
bool (a subclass of int!) |
Java pins every primitive's size in the language spec. That's part of "write once, run anywhere": an int is 32 bits on every JVM. C pins almost nothing: int is "at least 16 bits", long is 32 bits on 64-bit Windows but 64 bits on 64-bit Linux (the LLP64 versus LP64 data models). That's why portable C uses <stdint.h> types.
Java's lack of unsigned types bites in binary protocols and hashing: byte b = (byte) 0xFF; is −1, and b & 0xFF is the idiom to get 255.
Integer overflow
What happens when Integer.MAX_VALUE + 1 is evaluated is one of the sharpest differences between languages:
| Language | Default on overflow | Opt-in alternatives |
|---|---|---|
| Java | Silent wraparound (two's complement), defined behaviour: 2147483647 + 1 == -2147483648 |
Math.addExact (throws ArithmeticException), Math.multiplyHigh, BigInteger |
| C# / .NET | Wraps (an unchecked context by default) |
checked(a + b) or the project setting CheckForOverflowUnderflow throws OverflowException |
| Go | Wraps silently, defined | math/bits.Add64 for carry, math/big |
| C / C++ signed | Undefined behaviour. The optimiser may assume it never happens, so if (x + 1 < x) can be deleted |
__builtin_add_overflow, C23 ckd_add, -fwrapv, -ftrapv, UBSan |
| C / C++ unsigned | Wraps modulo 2ⁿ, defined | — |
| Rust | Panics in debug builds, wraps in release builds (configurable with overflow-checks) |
checked_add → Option, wrapping_add, saturating_add, overflowing_add, Wrapping<T> |
| Zig | Illegal behaviour: panics in Debug and ReleaseSafe, undefined in ReleaseFast/ReleaseSmall | Wrapping operators +%, saturating +|, @addWithOverflow |
| Python | Impossible: int grows |
— |
| JavaScript | number is a double: integers are exact only to 2⁵³; beyond that precision is lost |
BigInt |
int a = Integer.MAX_VALUE;
System.out.println(a + 1); // -2147483648: silent wraparound
System.out.println(Math.addExact(a, 1)); // throws ArithmeticException: integer overflow
// A classic bug: binary search midpoint
int mid = (low + high) / 2; // overflows for large arrays (the JDK had this bug until 2006)
int safe = (low + high) >>> 1; // unsigned shift fixes it
let a: i32 = i32::MAX;
// let b = a + 1; // debug build: panic "attempt to add with overflow"
assert_eq!(a.checked_add(1), None);
assert_eq!(a.wrapping_add(1), i32::MIN);
assert_eq!(a.saturating_add(1), i32::MAX);
let (v, overflowed) = a.overflowing_add(1); // (-2147483648, true)
const a: i32 = std.math.maxInt(i32);
// const b = a + 1; // compile error here (comptime-known); at run time: panic in safe modes
const w = a +% 1; // wrapping: -2147483648
const s = a +| 1; // saturating: 2147483647
const r = @addWithOverflow(a, 1); // .{ -2147483648, 1 }
#include <limits.h>
#include <stdckdint.h> // C23
int a = INT_MAX;
// int b = a + 1; // UNDEFINED BEHAVIOUR: compiler may assume it can't happen
int r;
if (ckd_add(&r, a, 1)) { /* overflow detected */ }
unsigned u = UINT_MAX; u += 1; // well-defined: 0
var a int32 = math.MaxInt32
fmt.Println(a + 1) // -2147483648: wraps, defined by the spec
int a = int.MaxValue;
Console.WriteLine(unchecked(a + 1)); // -2147483648
Console.WriteLine(checked(a + 1)); // throws OverflowException
The design spectrum shows the paradigms clearly. Java and Go choose defined but silent behaviour: predictable, never undefined, but bugs hide. C and C++ choose undefined, which gives the optimiser freedom at the cost of safety. Rust and Zig choose checked in development, explicit operators when you mean wrapping, so intent is visible in the source. Python removes the problem with arbitrary precision, at a speed cost.
Floating point
All of these languages use IEEE 754 binary floating point (float = 32 bits, double = 64 bits). The consequences are universal:
0.1 + 0.2 != 0.3in every language. Never compare floats with==unless you know the values are exactly representable. Compare with a tolerance.- Never use binary floats for money. Use
BigDecimal(Java),decimal(C#, a 128-bit decimal floating point),decimal.Decimal(Python),shopspring/decimal(Go),rust_decimal(Rust), or integers in minor units (cents). NaN != NaN. Java'sDouble.equalstreats NaN as equal to itself and distinguishes0.0from-0.0, while==does neither. That's whyDoublekeys in aHashMapbehave differently from==comparisons.- Java:
strictfphas been the default since JDK 17 (JEP 306), so floating-point results are now identical on every platform.
new BigDecimal("0.1").add(new BigDecimal("0.2")); // 0.3 exactly
new BigDecimal(0.1); // 0.1000000000000000055511151231257827… (the double's real value!)
new BigDecimal("2.0").equals(new BigDecimal("2.00")); // false: equals compares scale too; use compareTo == 0
Reference types and value types
This is the most important semantic split between languages. Ask: when I assign or pass a variable, is the data copied, or is a pointer to shared data copied?
| Language | Value types | Reference types |
|---|---|---|
| Java | Only the 8 primitives | Everything else: objects, arrays, strings, boxed Integer. Valhalla value classes (JEP 401, in preview builds, targeted after JDK 27) will add identity-free value objects |
| Kotlin | Same as Java at run time; @JvmInline value class wraps one value without allocation |
Classes |
| C# | struct, record struct, enums, primitives (all System.ValueType) |
class, record, arrays, string, delegates |
| Go | Everything is a value: structs and arrays are copied on assignment | Pointers *T are explicit. Slices, maps, channels, interfaces and funcs are small headers containing pointers, so copying them shares the underlying data |
| Rust | Everything is a value, and assignment moves (or copies, for Copy types) |
References &T/&mut T (borrowed, checked), and owning pointers Box<T>, Rc<T>, Arc<T> |
| C / C++ / Zig | Everything is a value | Pointers and C++ references are explicit |
| Python / JS / Ruby | None, conceptually: every variable is a reference to an object (small ints and strings are immutable, so they behave like values) | Everything |
Consequences you'll meet in backend code:
- Java
==on objects compares references (identity), not content.equalscompares content (chapter 35). - Boxing: Java generics need objects, so
List<Integer>stores a pointer to a separate heapIntegerper element: roughly 16 bytes of object plus a 4–8-byte reference instead of 4 bytes. That costs memory and cache misses (chapter 41). C#, Rust, C++, Go and Zig generics work over unboxed values. - Null: every Java reference can be
null. Kotlin, C# (with nullable reference types), Rust (Option<T>), Swift, TypeScript (strictNullChecks), Zig (?T) and Haskell (Maybe) make nullability part of the type, so the compiler forces you to handle the empty case. Go hasnilpointers, maps, slices and interfaces, plus the famous trap that an interface holding a nil pointer is not itself nil.
type MyErr struct{}
func (*MyErr) Error() string { return "boom" }
func find() error {
var e *MyErr = nil
return e // returns a NON-nil error interface: (type=*MyErr, value=nil)
}
// find() != nil is TRUE. Return a literal nil instead.
Operators and equality
Operators are mostly shared, but several semantics differ:
| Topic | Java | Others |
|---|---|---|
| Integer division | Truncates toward zero: -7 / 2 == -3, -7 % 2 == -1 |
Same in C, C++, Go, Rust, C#, Zig (@divTrunc; Zig makes you choose @divFloor/@divTrunc for signed values). Python floors: -7 // 2 == -4, -7 % 2 == 1. Use Math.floorMod in Java for a non-negative modulo |
| Shifts | >> arithmetic, >>> logical. Shift distance is masked (1 << 33 == 2 for int) |
C/C++: shifting by ≥ width is UB. Rust panics in debug. Go shifts by ≥ width give 0 (or −1 for negative arithmetic shifts) |
| Short-circuit | &&, \|\| short-circuit; &, \| on booleans don't |
Universal |
| Operator overloading | None for user types (only + on String) |
C++, C#, Kotlin (operator fun plus), Rust (impl Add), Python (__add__), Scala (methods named +) allow it. Go and Zig deliberately don't |
| Equality | == primitives by value, references by identity. equals() for content |
C#: == overloadable, records compare by value. Kotlin: == calls equals, === is identity. Go: == on comparable structs compares fields, and slices, maps and funcs aren't comparable. Rust: == via the PartialEq trait. Python: == (__eq__) versus is (identity). JS: === versus the coercing == |
| Ternary | c ? a : b |
Go has no ternary. Rust, Kotlin, Zig, Scala use if expressions |
| Increment | i++, ++i |
Go: i++ is a statement, not an expression. Rust, Python, Zig: no ++ at all (+= 1) |
The Integer cache trap combines boxing with identity:
Integer a = 127, b = 127;
System.out.println(a == b); // true: Integer.valueOf caches -128..127
Integer c = 128, d = 128;
System.out.println(c == d); // false: two different objects
System.out.println(c.equals(d)); // true
Control flow
All these languages have if, loops, break/continue and return. The differences are expressiveness and safety:
// Java: classic for, enhanced for, while, do-while, labeled break, switch expression
outer:
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == target) break outer; // labeled break exits both loops
}
}
String label = switch (status) { // switch expression (JDK 14): exhaustive, no fall-through
case PENDING, QUEUED -> "waiting";
case RUNNING -> "busy";
case DONE -> {
log.info("done");
yield "finished"; // yield returns a value from a block
}
};
// Go: one loop keyword. No while, no do-while. switch doesn't fall through by default.
for i := 0; i < n; i++ { } // classic
for cond { } // "while"
for { } // infinite
for i, v := range items { } // range over slices, maps, channels, strings, ints (1.22), iterators (1.23)
switch { // switch with no tag: a tidy if/else chain
case x < 0:
return "neg"
case x == 0:
return "zero"
// fallthrough would be explicit
}
// Rust: loop is an expression; break can return a value. if and match are expressions.
let found = 'outer: loop {
for row in &grid {
if row.contains(&target) { break 'outer true; }
}
break false;
};
let label = match status { // match must be exhaustive: compile error if a variant is missing
Status::Pending | Status::Queued => "waiting",
Status::Running => "busy",
Status::Done => "finished",
};
while let Some(job) = queue.pop() { run(job); } // loop while a pattern matches
// Zig: while with a continue expression, for over slices/ranges, labeled blocks as expressions
var i: usize = 0;
while (i < n) : (i += 1) { } // the ': (i += 1)' runs on each continue
for (items, 0..) |item, idx| { _ = item; _ = idx; }
const label = switch (status) { // exhaustive over enums
.pending, .queued => "waiting",
.running => "busy",
.done => "finished",
};
const v = blk: { // labeled block returns a value
if (x > 0) break :blk x;
break :blk 0;
};
# Python: for-else (else runs when the loop wasn't broken), match statement (3.10)
for user in users:
if user.banned:
break
else:
print("no banned users")
match command:
case {"op": "move", "x": x, "y": y}: # structural pattern matching on dicts/objects
move(x, y)
case _:
raise ValueError(command)
Exhaustiveness is the big modern theme: switch over an enum or a sealed hierarchy (chapter 39), and the compiler tells you when you forgot a case. Rust, Kotlin (when on sealed types), Scala, Haskell, Zig, Swift, TypeScript (with never checks), C# (warnings) and now Java (switch expressions and pattern switches) all do this. Go and C don't. A switch without a default in Go silently does nothing for unknown values.
Data: arrays and strings
Arrays
| Language | Fixed-size array | Growable | Bounds checks | Notes |
|---|---|---|---|---|
| Java | int[] (a heap object with a length field) |
ArrayList<E> |
Always (ArrayIndexOutOfBoundsException), often eliminated by the JIT |
Arrays are covariant (Object[] o = new String[1]; o[0] = 1; → ArrayStoreException at run time). Multi-dimensional arrays are arrays of arrays (jagged, not contiguous) |
| C# | int[], and true rectangular int[,] |
List<T> |
Always | Span<T>/Memory<T> give slices without copying |
| Go | [4]int is a value, and copying copies all elements |
Slices []int (pointer, len, cap) with append |
Always (panic) | append may or may not reallocate, so two slices can alias the same array, a classic Go bug |
| Rust | [i32; 4] (value) |
Vec<T> |
Always (panic), elided when provably safe | Slices &[T] are (ptr, len) fat pointers. get(i) returns Option |
| C | int a[4] |
Manual realloc |
None: out-of-bounds is UB (buffer overflows, CVEs) | Arrays decay to pointers when passed, losing their length |
| C++ | std::array<int,4> |
std::vector<T> |
at() checks; [] doesn't (unless hardened: C++26 standard library hardening) |
std::span<T> (C++20) for views |
| Zig | [4]i32 (value) |
std.ArrayList(T) (with an explicit allocator) |
Checked in Debug/ReleaseSafe | Slices []T carry a length. Sentinel-terminated types ([:0]u8) interoperate with C |
| Python | — | list (array of pointers to objects) |
Always (IndexError); negative indexes count from the end |
array/numpy for packed numeric data |
// The Go slice aliasing trap
a := make([]int, 3, 10) // len 3, cap 10
b := append(a, 4) // fits in capacity: b shares a's backing array
c := append(a, 5) // ALSO writes index 3 of the same backing array
fmt.Println(b[3]) // 5: b and c alias. Copy (slices.Clone) or use a full slice expression a[:3:3]
// Java: covariance makes this compile and fail at run time
Object[] objs = new String[2];
objs[0] = 42; // java.lang.ArrayStoreException: java.lang.Integer
// Generic collections are invariant instead: List<Object> lst = new ArrayList<String>(); // compile error (chapter 36)
// C: the array forgets its length when passed
void f(int a[]) { printf("%zu\n", sizeof a); } // prints 8: a is just an int*
int x[10]; f(x);
Strings
Strings look simple and are anything but. Ask four questions: what's the encoding, is it mutable, what does "length" count, and who owns the memory?
| Language | Representation | Mutable? | length counts |
Notes |
|---|---|---|---|---|
| Java | String: Latin-1 bytes or UTF-16 (compact strings, JDK 9) |
Immutable | UTF-16 code units ("😀".length() == 2) |
codePointCount, codePoints(). Literals are interned. Use StringBuilder for building |
| C# | UTF-16 | Immutable | UTF-16 code units | StringBuilder, Span<char>, Rune |
| Go | string = immutable byte sequence, UTF-8 by convention (not enforced) |
Immutable | bytes (len("é") == 2) |
range over a string yields runes (code points). []byte(s) copies. strings.Builder |
| Rust | String (owned, growable) and &str (borrowed slice). Guaranteed valid UTF-8 |
String is mutable |
bytes (.len()); .chars().count() gives code points |
No integer indexing (s[0] doesn't compile), because a byte index might split a character. Slicing must land on char boundaries or it panics |
| C | char*, NUL-terminated bytes |
Yes | strlen scans to \0 (O(n)) |
No length stored, so a missing \0 or strcpy overflow causes buffer overflows. Encoding is unspecified |
| C++ | std::string (bytes, with small-string optimisation), std::string_view |
Yes | bytes | std::u8string exists but is little used. string_view must not outlive its source |
| Zig | []const u8 slices, UTF-8 by convention |
Depends on the slice | bytes | No string type at all: strings are byte slices. std.unicode for decoding |
| Python 3 | str = sequence of code points (PEP 393: Latin-1, UCS-2 or UCS-4 internally) |
Immutable | code points (len("😀") == 1) |
bytes is separate. Must .encode()/.decode() explicitly |
| JavaScript | UTF-16 | Immutable | UTF-16 code units | Same "😀".length == 2 surprise as Java |
None of them count what users think of as characters: grapheme clusters ("👍🏽" is 2 code points; "é" can be 1 or 2). For user-visible text, use ICU (java.text.BreakIterator, ICU4J), unicode-segmentation in Rust, or Intl.Segmenter in JS. Vol. 1 ch. 2 covers encodings from first principles.
String s = "naïve 😀";
s.length(); // 8 (UTF-16 units: 😀 is a surrogate pair)
s.codePointCount(0, s.length()); // 7
s.getBytes(StandardCharsets.UTF_8).length; // 11
// Immutability: every concatenation in a loop creates a new String
String out = "";
for (String p : parts) out += p; // O(n²) copying in the worst case
var sb = new StringBuilder(); // O(n)
for (String p : parts) sb.append(p);
// (javac compiles a single a + b + c expression via invokedynamic StringConcatFactory, which is efficient)
let s = String::from("naïve 😀");
s.len(); // 11 bytes
s.chars().count(); // 7 Unicode scalar values
// let c = s[0]; // compile error: String cannot be indexed by integer
let first: Option<char> = s.chars().next();
let slice = &s[0..2]; // "na" (OK: byte range on char boundaries)
// &s[0..3] // panic: byte index 3 is inside 'ï'
s := "naïve 😀"
len(s) // 11 bytes
utf8.RuneCountInString(s) // 7
for i, r := range s { // i = byte offset, r = rune
fmt.Println(i, string(r))
}
s[2] // a byte (0xC3), not 'ï'
s = "naïve 😀"
len(s) # 7 code points
len(s.encode("utf-8")) # 11 bytes
s[6] # '😀'
Behaviour: methods, classes, interfaces
Methods and parameter passing
Java is always pass-by-value. For a primitive, the value is the number. For an object, the value is the reference. The callee gets a copy of the pointer, so it can mutate the object, but reassigning the parameter doesn't affect the caller (Vol. 1 ch. 3 has the memory diagram).
| Language | Passing | Overloading | Default / named args | Varargs |
|---|---|---|---|---|
| Java | By value (references copied) | Yes | Neither (use overloads or builders) | String... args (an array) |
| Kotlin | Same as Java | Yes | Both | vararg |
| C# | By value. ref, out and in give by-reference |
Yes | Both | params |
| Go | By value (copies structs). Pass *T to mutate |
No | Neither (functional options pattern instead) | ...T (a slice) |
| Rust | Move by default; &T/&mut T borrow |
No (traits give similar flexibility) | Neither (builders, Default) |
No (macros like println! are variadic) |
| C | By value; pointers to mutate | No (_Generic macros fake it) |
No | ... with va_list (unsafe) |
| C++ | Value, T&, const T&, T&& (move) |
Yes | Defaults yes, named no | Variadic templates |
| Zig | By value semantically. The compiler may pass large params by reference since params are immutable | No | No (anonymous struct literals act like named args) | No (anytype tuples, as in print("{s}", .{x})) |
| Python | "Pass by object reference" (like Java's) | No (last definition wins; functools.singledispatch) |
Both, plus *args, **kwargs |
Yes |
static void reassign(StringBuilder sb) { sb = new StringBuilder("new"); } // caller unaffected
static void mutate(StringBuilder sb) { sb.append("!"); } // caller sees "!"
Methods versus functions: Java has no free functions. Everything lives in a class (static methods are free functions in disguise, such as Math.max). Go, Rust, C, C++, Zig, Python and Kotlin have free functions. Rust and Go attach methods to types outside the type definition (impl Point { … }, func (p Point) Norm() float64). Go's receiver choice (p Point versus p *Point) decides whether the method sees a copy.
Classes
A class bundles state (fields) with behaviour (methods) and controls access. Which languages have them:
- Java, C#, C++, Kotlin, Scala, Python, TypeScript, Swift: classes with constructors, inheritance and access modifiers.
- Go: no classes. Structs + methods + embedding (embedding promotes the embedded type's methods, which is composition, not inheritance).
- Rust: no classes. Structs/enums +
implblocks + traits. No implementation inheritance at all. - Zig: structs with methods (functions in the struct namespace, called with
.sugar). No inheritance, no hidden constructors:initis a convention. - C: structs + functions taking a struct pointer; "classes" are a convention (
FILE*andfopen/fclose). - Erlang/Elixir: no objects; processes hold state (chapter 38).
- Haskell: data types + type classes (an ancestor of Rust traits).
public final class Account {
private final String id; // encapsulated state
private long balanceCents;
public Account(String id) { this.id = Objects.requireNonNull(id); }
public void deposit(long cents) {
if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
balanceCents += cents; // invariant maintained by the only mutator
}
public long balance() { return balanceCents; }
}
type Account struct {
id string // lowercase: unexported outside the package
balanceCents int64
}
func NewAccount(id string) *Account { return &Account{id: id} } // constructor convention
func (a *Account) Deposit(cents int64) error { // pointer receiver: mutates
if cents <= 0 {
return errors.New("amount must be positive")
}
a.balanceCents += cents
return nil
}
func (a *Account) Balance() int64 { return a.balanceCents }
pub struct Account {
id: String, // private to the module by default
balance_cents: i64,
}
impl Account {
pub fn new(id: impl Into<String>) -> Self { Self { id: id.into(), balance_cents: 0 } }
pub fn deposit(&mut self, cents: i64) -> Result<(), String> { // &mut self: exclusive access
if cents <= 0 { return Err("amount must be positive".into()); }
self.balance_cents += cents;
Ok(())
}
pub fn balance(&self) -> i64 { self.balance_cents }
}
pub const Account = struct {
id: []const u8,
balance_cents: i64 = 0,
pub fn init(id: []const u8) Account { return .{ .id = id }; }
pub fn deposit(self: *Account, cents: i64) error{InvalidAmount}!void {
if (cents <= 0) return error.InvalidAmount;
self.balance_cents += cents;
}
pub fn balance(self: Account) i64 { return self.balance_cents; }
};
// Note: Zig has no field privacy; all fields are visible. Encapsulation is by convention.
public sealed class Account(string id) // primary constructor (C# 12)
{
public string Id { get; } = id ?? throw new ArgumentNullException(nameof(id));
public long BalanceCents { get; private set; }
public void Deposit(long cents)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(cents);
BalanceCents += cents;
}
}
class Account:
def __init__(self, id: str):
self._id = id # leading underscore: "private" by convention only
self._balance_cents = 0
def deposit(self, cents: int) -> None:
if cents <= 0:
raise ValueError("amount must be positive")
self._balance_cents += cents
@property
def balance(self) -> int:
return self._balance_cents
Interfaces
An interface is a contract: a set of operations a type promises to support. The deep difference is nominal versus structural typing:
| Approach | Languages | How a type "implements" |
|---|---|---|
| Nominal, declared | Java, C#, Kotlin, Scala, TypeScript classes (implements is checked nominally only for the declaration) |
class A implements Runnable, declared at the type's definition |
| Structural, implicit | Go interfaces, TypeScript (all types), Python Protocol (static checkers) |
If it has the methods, it satisfies the interface. No declaration. You can define an interface after the fact for types you don't own |
| Traits, declared separately | Rust traits, Haskell type classes, Scala given instances, Swift protocol extensions |
impl Display for Point { … } can be written separately from the type (subject to the orphan rule: you must own the trait or the type) |
| Templates/compile-time duck typing | C++ templates (constrained by C++20 concepts), Zig anytype/comptime |
The code compiles if the operations exist when instantiated |
| Hand-made vtables | C, Zig runtime polymorphism (std.mem.Allocator is { ptr, vtable }) |
A struct of function pointers |
public interface Notifier {
void send(String to, String msg);
default void sendAll(List<String> to, String msg) { to.forEach(t -> send(t, msg)); } // default method (Java 8)
static Notifier noop() { return (t, m) -> {}; } // static factory
}
public final class EmailNotifier implements Notifier { // nominal: must declare
public void send(String to, String msg) { /* SMTP */ }
}
type Notifier interface {
Send(to, msg string) error
}
type EmailNotifier struct{}
func (EmailNotifier) Send(to, msg string) error { return nil } // satisfies Notifier implicitly
// Convention: "accept interfaces, return structs". Consumers define small interfaces they need.
var _ Notifier = EmailNotifier{} // compile-time assertion that it satisfies the interface
pub trait Notifier {
fn send(&self, to: &str, msg: &str) -> Result<(), SendError>;
fn send_all(&self, to: &[&str], msg: &str) -> Result<(), SendError> { // default method
to.iter().try_for_each(|t| self.send(t, msg))
}
}
struct EmailNotifier;
impl Notifier for EmailNotifier {
fn send(&self, _to: &str, _msg: &str) -> Result<(), SendError> { Ok(()) }
}
// Static dispatch (monomorphised, inlinable): fn notify(n: &impl Notifier)
// Dynamic dispatch (vtable, like Java): fn notify(n: &dyn Notifier)
// C++20: concept (compile-time interface) versus virtual base class (runtime interface)
template <typename T>
concept Notifier = requires(T n, std::string_view to, std::string_view msg) {
{ n.send(to, msg) } -> std::same_as<void>;
};
void notify(Notifier auto& n) { n.send("ops", "disk full"); } // checked at instantiation, no vtable
struct INotifier { virtual ~INotifier() = default; virtual void send(std::string_view, std::string_view) = 0; };
// Zig: comptime duck typing; or an explicit fat-pointer interface for runtime polymorphism
fn notify(n: anytype) void { // instantiated per type; compile error if n.send doesn't exist
n.send("ops", "disk full");
}
const Notifier = struct { // runtime interface: pointer + function table
ptr: *anyopaque,
sendFn: *const fn (ptr: *anyopaque, to: []const u8, msg: []const u8) void,
pub fn send(self: Notifier, to: []const u8, msg: []const u8) void { self.sendFn(self.ptr, to, msg); }
};
from typing import Protocol
class Notifier(Protocol): # structural: any class with send() matches for type checkers
def send(self, to: str, msg: str) -> None: ...
class EmailNotifier: # no inheritance needed
def send(self, to: str, msg: str) -> None: ...
def notify(n: Notifier) -> None: n.send("ops", "disk full")
Dispatch cost: Java interface calls are virtual (dynamic dispatch through itables/vtables), but the JIT devirtualises and inlines monomorphic and bimorphic call sites using runtime profiling (chapter 40). Rust and C++ choose at the call site: generics are monomorphised (static, zero-cost, larger binaries) and dyn/virtual is dynamic. Go interface calls are always dynamic through an itab, with limited devirtualisation (profile-guided optimisation helps).
Packages, modules and visibility
| Language | Unit of code | Visibility levels |
|---|---|---|
| Java | Package (a directory/namespace) inside a module (JPMS, chapter 42) | private (class), package-private (default, no keyword), protected (package + subclasses), public. With JPMS, public is visible outside the module only if the package is exports-ed |
| Kotlin | Package; module = compilation unit | private, protected, internal (same module), public (default) |
| C# | Namespace (logical) and assembly (physical) | private, protected, internal (assembly), public, file |
| Go | Package = directory; module = versioned set of packages (go.mod) |
Capitalisation: Exported versus unexported. internal/ directories are importable only by the parent tree |
| Rust | Module tree inside a crate (compilation unit); packages hold crates | Private by default; pub, pub(crate), pub(super), pub(in path) |
| C | Translation unit (.c plus included headers) |
static at file scope = internal linkage (file-private); otherwise external. Headers declare the "public API" |
| C++ | Namespaces (naming) + headers or C++20 modules (export module) |
private/protected/public for class members; anonymous namespaces for file-private |
| Zig | Each file is a struct; @import returns it |
pub or file-private. No field privacy |
| Python | Module = file; package = directory | Convention only (_private), plus __all__ for import * |
| TypeScript/Node | ES modules (files) | export or not. #private class fields are truly private at run time |
Java's package-private default is underused and valuable: put an implementation class package-private next to its public interface, and nothing outside the package can depend on it.
Modelling data: enums and records
Enums
The word "enum" covers two very different things:
- Named constants (C, C++
enum class, C#, Goiota): integers with names. - Sum types / tagged unions / algebraic data types (Rust
enum, Haskelldata, Zigunion(enum), Kotlin and Java sealed hierarchies, Scala 3enum, TypeScript discriminated unions, Swiftenumwith payloads): a value is one of several variants, each with its own data, and the compiler checks you handle all of them.
Java enums sit in between: each constant is a singleton object of a class that can have fields, constructors, methods, and even per-constant method bodies. They aren't integers (the ordinal() exists but shouldn't be persisted), and they can't carry per-instance data that varies at run time. For that, Java uses sealed interfaces + records (chapter 39).
public enum OrderStatus {
PENDING("Awaiting payment") { @Override boolean cancellable() { return true; } },
PAID("Paid"),
SHIPPED("On the way"),
CANCELLED("Cancelled");
private final String label;
OrderStatus(String label) { this.label = label; }
public String label() { return label; }
boolean cancellable() { return false; }
}
// EnumSet/EnumMap are bit-vector/array backed and very fast.
// Persist name() (or an explicit code), never ordinal(): reordering constants silently corrupts data.
// JPA: @Enumerated(EnumType.STRING), not the ORDINAL default.
// For variants carrying different data: a sealed hierarchy (chapter 39)
sealed interface Payment permits Card, BankTransfer, Wallet {}
record Card(String last4) implements Payment {}
record BankTransfer(String iban) implements Payment {}
record Wallet(String provider, String token) implements Payment {}
// Rust enums ARE sum types: each variant may carry different data
enum Payment {
Card { last4: String },
BankTransfer { iban: String },
Wallet { provider: String, token: String },
}
fn describe(p: &Payment) -> String {
match p { // exhaustive
Payment::Card { last4 } => format!("card ••{last4}"),
Payment::BankTransfer { iban } => format!("IBAN {iban}"),
Payment::Wallet { provider, .. } => format!("{provider} wallet"),
}
}
// Option<T> and Result<T, E> are ordinary library enums built this way.
// Go has no enums: typed constants with iota, and no exhaustiveness checking
type OrderStatus int
const (
Pending OrderStatus = iota // 0
Paid // 1
Shipped // 2
Cancelled // 3
)
func (s OrderStatus) String() string { // `go generate` + stringer automates this
switch s {
case Pending: return "Pending"
case Paid: return "Paid"
}
return fmt.Sprintf("OrderStatus(%d)", int(s))
}
// Any int converts: OrderStatus(42) compiles. Linters (exhaustive) add checks.
const Payment = union(enum) { // tagged union: tag + payload, exhaustive switch
card: struct { last4: [4]u8 },
bank_transfer: []const u8,
wallet: struct { provider: []const u8, token: []const u8 },
};
fn describe(p: Payment) []const u8 {
return switch (p) {
.card => "card",
.bank_transfer => "bank",
.wallet => |w| w.provider,
};
}
/* C: plain integers, plus a hand-rolled tagged union (no checking) */
enum status { PENDING, PAID, SHIPPED, CANCELLED };
struct payment {
enum { CARD, BANK, WALLET } kind;
union { char last4[5]; char iban[35]; struct { char provider[16]; char token[64]; } wallet; } as;
};
/* Reading p.as.iban when kind == CARD compiles fine and reads garbage. */
// TypeScript: discriminated unions + never for exhaustiveness
type Payment =
| { kind: "card"; last4: string }
| { kind: "bank"; iban: string }
| { kind: "wallet"; provider: string; token: string };
function describe(p: Payment): string {
switch (p.kind) {
case "card": return `card ••${p.last4}`;
case "bank": return `IBAN ${p.iban}`;
case "wallet": return `${p.provider} wallet`;
default: { const never: never = p; return never; } // compile error if a variant is unhandled
}
}
-- Haskell: the original algebraic data type
data Payment = Card String | BankTransfer String | Wallet { provider :: String, token :: String }
describe :: Payment -> String
describe (Card l4) = "card " ++ l4
describe (BankTransfer i) = "IBAN " ++ i
describe (Wallet p _) = p ++ " wallet"
Sum types plus product types (structs/records: a value has field A and field B) are algebraic data types. They let you make illegal states unrepresentable: instead of a class with nullable cardLast4, iban and walletToken fields where exactly one should be set, model the three variants so a "card with an IBAN" can't exist.
Records and data classes
Much backend code moves plain data: DTOs, events, query results, value objects. Writing constructor, getters, equals, hashCode and toString by hand is error-prone (forget a field in equals and you get subtle bugs). Every modern language generates them:
// Java record (JDK 16): a transparent, shallowly immutable data carrier
public record Money(BigDecimal amount, Currency currency) {
public Money { // compact canonical constructor: validation
Objects.requireNonNull(amount); Objects.requireNonNull(currency);
if (amount.scale() > currency.getDefaultFractionDigits())
throw new IllegalArgumentException("too many decimals");
}
public Money plus(Money o) { // "withers" return new instances
if (!currency.equals(o.currency)) throw new IllegalArgumentException("currency mismatch");
return new Money(amount.add(o.amount), currency);
}
}
// Generated: private final fields, accessors amount()/currency() (not getAmount),
// equals/hashCode over all components, toString. Records are final and cannot extend classes.
// Shallow: a record holding a List can still have that list mutated. Copy defensively (List.copyOf).
data class Money(val amount: BigDecimal, val currency: Currency) {
init { require(amount.scale() <= currency.defaultFractionDigits) }
operator fun plus(o: Money): Money {
require(currency == o.currency)
return copy(amount = amount + o.amount) // copy() with named args
}
}
val (amt, cur) = money // destructuring via componentN()
public sealed record Money(decimal Amount, string Currency)
{
public Money Plus(Money o) =>
Currency == o.Currency ? this with { Amount = Amount + o.Amount } // non-destructive mutation
: throw new InvalidOperationException("currency mismatch");
}
// record struct gives a value-type version; records get value equality and ToString.
#[derive(Debug, Clone, PartialEq, Eq, Hash)] // opt in to each capability explicitly
pub struct Money {
amount_minor: i64, // store minor units (cents)
currency: Currency,
}
impl Money {
pub fn plus(&self, o: &Money) -> Result<Money, CurrencyMismatch> {
if self.currency != o.currency { return Err(CurrencyMismatch); }
Ok(Money { amount_minor: self.amount_minor + o.amount_minor, ..self.clone() })
}
}
// Go structs compare with == if all fields are comparable; no generated methods needed
type Money struct {
AmountMinor int64
Currency string
}
func (m Money) Plus(o Money) (Money, error) { // value receiver: m is a copy, so m is effectively immutable
if m.Currency != o.Currency {
return Money{}, errors.New("currency mismatch")
}
return Money{m.AmountMinor + o.AmountMinor, m.Currency}, nil
}
// Note: no way to force validation through a constructor; Money{} literals bypass it.
from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True, slots=True)
class Money:
amount: Decimal
currency: str
def __post_init__(self):
if self.amount.as_tuple().exponent < -2:
raise ValueError("too many decimals")
def plus(self, o: "Money") -> "Money":
if self.currency != o.currency:
raise ValueError("currency mismatch")
return Money(self.amount + o.amount, self.currency)
Records are value-based in equality, but on the JVM they still have identity (== compares references, and they can be synchronised on). Valhalla value classes will remove identity, allowing the JVM to flatten them into arrays and fields like C structs.
Errors
Error handling models
How a language reports failure shapes every API you write. There are five main models:
Exceptions (Java, C#, C++, Python, Kotlin, Scala, JS): failure unwinds the stack to the nearest matching catch. The happy path stays clean and errors carry stack traces, but any call might throw, and the control flow is invisible in the source.
Java's checked exceptions are unique among mainstream languages: subclasses of Exception (but not RuntimeException) must be declared in throws or caught. The idea is that the type system documents recoverable failures. In practice:
- They don't compose with lambdas:
Function<T,R>can't throwIOException, so you see wrapping intoUncheckedIOException. - They leak implementation details through interface signatures (
throws SQLExceptionfrom a repository interface). - Kotlin, Scala, C# and Groovy dropped them. Modern Java style, including Spring, uses unchecked exceptions for most failures (Spring translates
SQLExceptioninto its uncheckedDataAccessExceptionhierarchy). - Use them where the caller can genuinely and specifically recover, and keep exceptions for exceptional conditions, not for control flow (exceptions are slow when stack traces are filled in: override
fillInStackTraceor use the constructor withwritableStackTrace=falsefor hot, expected failures).
// Hierarchy: Throwable → Error (don't catch: OutOfMemoryError, StackOverflowError)
// → Exception → RuntimeException (unchecked) / others (checked)
public Order load(Path p) throws IOException { // checked: callers must handle or declare
try (var in = Files.newBufferedReader(p)) { // try-with-resources: closes in reverse order,
return parse(in); // adds close() failures as suppressed exceptions
} catch (JsonParseException e) {
throw new InvalidOrderException("bad order file " + p, e); // ALWAYS chain the cause
}
}
// Multi-catch, and rethrow with precise types
try { work(); } catch (IOException | TimeoutException e) { retry(e); }
// Anti-patterns: catch (Exception e) {} swallowing; logging AND rethrowing (duplicate logs);
// returning null on error; exceptions for expected branches in hot loops.
// Errors are values; functions return (T, error). Wrap with %w to keep the chain.
func Load(path string) (*Order, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open order %s: %w", path, err)
}
defer f.Close() // runs when the function returns (any path)
o, err := parse(f)
if err != nil {
return nil, fmt.Errorf("parse order %s: %w", path, err)
}
return o, nil
}
// Inspecting chains
if errors.Is(err, fs.ErrNotExist) { /* sentinel match anywhere in the chain */ }
var pe *ParseError
if errors.As(err, &pe) { /* typed match, pe populated */ }
// panic/recover exist for truly unrecoverable bugs (nil map write, index out of range).
// net/http recovers panics per request so one bad handler doesn't kill the server.
// Result<T, E> + the ? operator: explicit in the signature, concise at the call site
#[derive(Debug, thiserror::Error)]
pub enum LoadError {
#[error("open {path}: {source}")]
Io { path: PathBuf, #[source] source: std::io::Error },
#[error("parse: {0}")]
Parse(#[from] serde_json::Error), // From impl lets ? convert automatically
}
pub fn load(path: &Path) -> Result<Order, LoadError> {
let text = std::fs::read_to_string(path)
.map_err(|e| LoadError::Io { path: path.into(), source: e })?;
let order = serde_json::from_str(&text)?; // ? = return early with the converted error
Ok(order)
}
// Libraries: precise error enums (thiserror). Applications: anyhow::Result with .context("…").
// panic! is for bugs/invariant violations; it unwinds (or aborts) the thread.
// #[must_use] on Result: ignoring it is a compiler warning.
// Error unions: !T is "error set or T". try = propagate; catch = handle; errdefer = cleanup on error only.
const LoadError = error{ NotFound, InvalidFormat } || std.fs.File.OpenError;
fn load(alloc: std.mem.Allocator, path: []const u8) !Order {
const file = try std.fs.cwd().openFile(path, .{});
defer file.close();
const buf = try file.readToEndAlloc(alloc, 1 << 20);
errdefer alloc.free(buf); // freed only if a later step fails
return parse(buf) catch |err| switch (err) {
error.UnexpectedToken => error.InvalidFormat,
else => |e| e,
};
}
// Errors are cheap integers (no allocation, no message); error return traces show the propagation path in debug builds.
// C++: exceptions (zero-cost on the happy path, table-driven unwinding) or std::expected (C++23)
std::expected<Order, LoadError> load(const std::filesystem::path& p) {
std::ifstream in(p);
if (!in) return std::unexpected(LoadError::NotFound);
return parse(in); // RAII destructors clean up on every exit path
}
// noexcept on move constructors matters: std::vector only moves elements during reallocation if moves can't throw.
// Many codebases (Google, games, embedded) build with -fno-exceptions.
/* C: return codes + errno; cleanup with goto */
int load(const char *path, struct order *out) {
int rc = -1;
FILE *f = fopen(path, "r");
if (!f) { perror("fopen"); return -1; } /* errno set by fopen */
char *buf = malloc(4096);
if (!buf) goto close_file;
if (parse(f, buf, out) != 0) goto free_buf;
rc = 0;
free_buf:
free(buf);
close_file:
fclose(f);
return rc;
}
# Elixir/Erlang: tagged tuples for expected failures; crashes for unexpected ones
def load(path) do
with {:ok, text} <- File.read(path),
{:ok, order} <- Jason.decode(text) do
{:ok, order}
else
{:error, reason} -> {:error, {:load_failed, path, reason}}
end
end
# Unexpected failures: let the process crash. Its supervisor restarts it in a known-good state.
# Failure is isolated because processes share no memory (chapter 38).
class InvalidOrder(Exception):
pass
def load(path: str) -> Order:
try:
with open(path) as f: # context manager closes the file
return parse(f)
except json.JSONDecodeError as e:
raise InvalidOrder(f"bad order file {path}") from e # 'from' chains the cause
Resource cleanup is tied to error handling, because every exit path must release files, locks and connections. Each language has a mechanism:
| Language | Cleanup mechanism |
|---|---|
| Java | try-with-resources on AutoCloseable; finally. Finalizers are deprecated for removal; Cleaner is a last-resort safety net |
| C# | using declarations on IDisposable/IAsyncDisposable |
| C++ / Rust | RAII: destructors (Drop) run deterministically at scope end, on every path including unwinding |
| Go | defer (function-scoped, LIFO) |
| Zig | defer and errdefer (block-scoped) |
| Python | with context managers |
| C | Manual: the goto cleanup idiom (GCC/Clang __attribute__((cleanup)) as an extension) |
Metadata: annotations and their cousins
Annotations
Annotations attach metadata to code elements. They don't do anything themselves: tools read them, either at compile time (annotation processors) or at run time (reflection). Spring, JPA, Jackson, Bean Validation and JUnit are built on them.
@Target({ElementType.METHOD, ElementType.TYPE}) // where it can be placed
@Retention(RetentionPolicy.RUNTIME) // SOURCE (discarded by javac), CLASS (in bytecode, default), RUNTIME (reflection)
@Documented
public @interface Audited {
String action(); // elements: primitives, String, Class, enums, annotations, arrays of these
boolean includeArgs() default false;
}
@Audited(action = "order.cancel", includeArgs = true)
public void cancel(OrderId id) { … }
// Runtime reading (what Spring AOP effectively does):
Audited a = method.getAnnotation(Audited.class);
if (a != null) audit(a.action(), a.includeArgs() ? args : null);
Three ways annotations take effect:
- Runtime reflection: Spring scans for
@Component/@Transactional, creates proxies (chapter 46), and Jackson reads@JsonProperty. Flexible, but costs startup time and is invisible to the compiler. GraalVM native images need reflection metadata, which Spring AOT generates (chapter 47). - Annotation processors (JSR 269) run inside
javacand generate new source files: MapStruct mappers, Dagger and Micronaut DI wiring, JPA metamodels,record-builder. Errors surface at compile time and nothing is reflective at run time. (Lombok is different: it uses internal javac APIs to modify the AST, which is why it breaks on new JDKs and needs agent and--add-openstricks.) - Bytecode instrumentation: Java agents and build plugins rewrite classes (Hibernate bytecode enhancement, OpenTelemetry's agent).
The same need is met very differently elsewhere:
| Language | Mechanism | Example |
|---|---|---|
| C# | Attributes (runtime reflection) + source generators (compile time) | [HttpGet("{id}")], [JsonPropertyName("id")], System.Text.Json source-gen |
| Kotlin | Java-compatible annotations + KSP (Kotlin Symbol Processing) + compiler plugins | @Serializable (kotlinx.serialization is a compiler plugin) |
| Rust | Attributes + procedural macros that transform token streams at compile time | #[derive(Serialize, Deserialize)], #[tokio::main], #[serde(rename = "id")] |
| Go | Struct tags (strings read via reflection) + //go: directives + go generate code generation |
`json:"id,omitempty" db:"order_id"`, //go:embed, //go:generate mockgen … |
| C++ | Standard attributes are compiler hints only ([[nodiscard]], [[likely]], [[deprecated]]). Static reflection was adopted for C++26 (P2996), with library and compiler support arriving gradually |
— |
| C | Compiler-specific __attribute__((…)), C23 [[nodiscard]] |
— |
| Zig | None needed: comptime code inspects types directly with @typeInfo and generates behaviour |
std.json.stringify walks struct fields at compile time |
| Python | Decorators: functions that wrap or register functions and classes at import time (much more than metadata) | @app.get("/orders/{id}"), @dataclass, @functools.cache |
| TypeScript | Decorators: the TC39 standard (TS 5.0+) and the older experimentalDecorators used by Angular and NestJS |
@Controller("orders") |
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)] // procedural macros generate the impls at compile time
#[serde(rename_all = "camelCase")]
struct OrderDto {
order_id: u64, // serialised as "orderId"
#[serde(skip_serializing_if = "Option::is_none")]
coupon: Option<String>,
}
type OrderDto struct {
OrderID uint64 `json:"orderId"` // struct tags read by encoding/json via reflection
Coupon *string `json:"coupon,omitempty"`
}
// comptime reflection: no annotations, the serializer inspects the type itself
const OrderDto = struct { order_id: u64, coupon: ?[]const u8 = null };
fn printFields(comptime T: type) void {
inline for (@typeInfo(T).@"struct".fields) |f| { // unrolled at compile time
std.debug.print("{s}: {s}\n", .{ f.name, @typeName(f.type) });
}
}
from functools import wraps
def audited(action: str): # a decorator factory: real code, runs at import time
def deco(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
audit_log(action, args)
return fn(*args, **kwargs)
return wrapper
return deco
@audited("order.cancel")
def cancel(order_id: int) -> None: ...
[AttributeUsage(AttributeTargets.Method)]
public sealed class AuditedAttribute(string action) : Attribute
{
public string Action { get; } = action;
}
[Audited("order.cancel")]
public void Cancel(OrderId id) { }
The paradigm lesson: Java and C# lean on runtime reflection (flexible, slower startup, harder AOT). Rust, Zig and Kotlin lean on compile-time generation (fast, checked, harder to write). Go deliberately keeps metadata minimal (tags plus explicit code generation). Python's decorators are ordinary code. Spring's shift toward AOT processing (chapter 47) moves Java toward the compile-time end.
Lab: the language's sharp edges, measured
Run on JDK 21 (java -Dstdout.encoding=UTF-8 Lab.java, since Java prints ₹ as ? when the terminal's default encoding isn't UTF-8, an encoding trap in itself). Each experiment is a bug that has reached production in real systems.
Experiment 1: silent integer overflow
int max = Integer.MAX_VALUE;
System.out.println("Integer.MAX_VALUE + 1 = " + (max + 1));
Math.addExact(max, 1); // throws instead of wrapping
long paise = 2_500_000_000L; int truncated = (int) paise;
Integer.MAX_VALUE + 1 = -2147483648
Math.addExact: integer overflow
(int) 2,500,000,000L = -1794967296
int arithmetic wraps silently (two's complement, Volume 1 chapter 6), and narrowing casts drop high bits without warning. ₹2.5 crore in paise is 2.5 billion, which doesn't fit in an int: a daily-revenue counter or an order total in paise can cross that line in a real business. Use long for money in minor units (or BigDecimal with an explicit scale for currency arithmetic), and Math.addExact/multiplyExact/toIntExact where overflow must be an error. Rust panics on overflow in debug builds, C# has checked blocks, and Go and Kotlin wrap like Java.
Experiment 2: the Integer cache and ==
Integer x = 127, y = 127, p = 128, q = 128;
Integer 127 == 127: true | 128 == 128: false | 128 equals 128: true
Boxing int into Integer reuses cached objects for −128 to 127, so == (reference comparison) happens to work for small numbers and then fails for larger ones. This bug passes every test with small ids and breaks in production when ids grow past 127. Compare boxed numbers (and all objects) with equals, or unbox first; IDEs and static analysis (Error Prone, SpotBugs, IntelliJ) flag == on boxed types.
Experiment 3: building strings in a loop
Appending 20,000 numbers to a string, two ways (third run, after JIT warm-up):
String s = ""; for (int i = 0; i < 20_000; i++) s += i; // creates a new string each time
var sb = new StringBuilder(); for (int i = 0; i < 20_000; i++) sb.append(i);
20,000 appends: += 992.6 ms | StringBuilder 0.36 ms | same result: true
Because strings are immutable, each += copies the whole string so far: O(n²) work, about 2,700× slower here. The compiler optimises a single expression like a + b + c, but not concatenation across loop iterations. Use StringBuilder, String.join or Collectors.joining when building strings in loops (and a real JSON library instead of string formatting for JSON, which also handles escaping quotes in names like "Sharma's").
Experiment 4: the cost of boxing
Summing five million numbers stored as int[] and as List<Integer>:
sum of 5M ints: int[] 5.7 ms | List<Integer> 18.7 ms | equal: true
An int[] is one contiguous block of 4-byte values; a List<Integer> is an array of references to separate 16-byte objects scattered across the heap, so summing it chases pointers and unboxes each one (Volume 1 chapter 7's cache lesson). The memory cost is larger still: roughly 4 bytes per element versus about 20. For large numeric data use primitive arrays or primitive-specialised collections (Eclipse Collections, fastutil) and primitive streams (IntStream); Project Valhalla's value classes aim to remove this penalty in a future JDK.
Experiment 5: exceptions are not free
100,000 throw-and-catch cycles, with a normal exception and with one that skips capturing its stack trace (super(message, null, false, false)):
100,000 throws: with stack traces 67.1 ms | without 1.7 ms
Almost all of an exception's cost is filling in the stack trace (walking the call stack and recording every frame). That's fine for genuinely exceptional situations, and the stack trace is invaluable when debugging. It's a problem when exceptions are used for control flow on hot paths: parsing user input with Integer.parseInt in a try/catch for every value, or validation that throws for every invalid field in a large import. Check first (or return a result type) on hot paths, and keep exceptions for the exceptional.
Try it yourself
- Change experiment 2's numbers to
LongandShort. Which ranges are cached? Then tryInteger.valueOf(1000) == Integer.valueOf(1000)with-XX:AutoBoxCacheMax=2000. - Rewrite experiment 3 using
Collectors.joining()over anIntStream. How does it compare? - Measure the memory of experiment 4's two collections with
jcmd <pid> GC.class_histogramwhile the program sleeps. - Port experiment 1 to Go, Rust (debug and
--release) and C#. Which ones wrap, which panic, and which offer checked arithmetic?
Revision sheet: language foundations
Key ideas
- Java compiles to bytecode for the JVM; static typing with local inference (
var); classes in packages;mainas the entry point (compact source files since JDK 25). - Primitives vs references: eight primitives hold values; everything else is a reference to a heap object; boxing bridges them (with caching and cost).
- Numbers: fixed-width two's-complement integers that wrap; IEEE 754 doubles;
Math.*Exact;BigDecimalfor decimal money;longpaise for amounts. - Equality:
==for primitives and identity;equals/hashCodefor value equality, which must be consistent (records generate both). - Strings: immutable, UTF-16 internally (compact Latin-1 storage when possible),
StringBuilderfor building, text blocks andformatted. - Data modelling: records for immutable data, enums for closed sets, sealed interfaces plus records for algebraic data types, pattern matching in
switch. - Behaviour: classes with encapsulated state, interfaces (with default and static methods), lambdas implementing functional interfaces.
- Errors: checked vs unchecked exceptions, try-with-resources, exception chaining; compared with Go's error values, Rust's
Result, C#/Kotlin unchecked-only. - Annotations: metadata for compilers, frameworks and tools (retention, targets, processors).
Numbers to remember
int±2.1 billion;long±9.2 × 10¹⁸; Integer cache −128 to 127.- Lab:
+=in a loop was about 2,700× slower thanStringBuilderfor 20,000 appends;List<Integer>about 3× slower to sum thanint[]; exceptions about 40× cheaper without stack traces.
Pitfalls
==on strings and boxed numbers;equalswithouthashCode.- Integer overflow in totals, counters and
(int)casts;doublefor money. - String concatenation in loops; hand-built JSON without escaping.
- Swallowed exceptions (
catch (Exception e) {}); exceptions for control flow on hot paths. - Mutable fields in objects used as map keys.
- Platform-default charsets when reading or writing bytes (use UTF-8 explicitly; it's the default since JDK 18).
Glossary
- Bytecode: the JVM's portable instruction format.
- Boxing: wrapping a primitive in its object type (
int→Integer). - Record: a transparent, immutable data class with generated members.
- Sealed type: a class or interface whose permitted subtypes are listed, enabling exhaustive pattern matching.
- Checked exception: an exception the compiler requires you to catch or declare.
- Functional interface: an interface with one abstract method, implementable by a lambda.