The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

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.

37 topics · ~56 min read · 32-question quiz
Updated Suggest a correction

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:

Java
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.

Java
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);
Text
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:

Java
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); }
}
Text
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:

Java
String a = "dosa", b = new String("dosa");
System.out.println("a == b: " + (a == b) + " | a.equals(b): " + a.equals(b));
Text
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:

Java
String meal = switch (dosa.category()) {
    case BREAKFAST -> "morning";
    case LUNCH -> "noon";
    case SNACKS -> "evening";
};

The enhanced for loops over arrays and collections:

Java
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:

Java
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):

Java
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:

Java
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: if is 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"); } }

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:

Interactive diagram: == on boxed integers: why 127 matches and 128 doesn't. It needs JavaScript; the text around it says the same.
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

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.3 in 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's Double.equals treats NaN as equal to itself and distinguishes 0.0 from -0.0, while == does neither. That's why Double keys in a HashMap behave differently from == comparisons.
  • Java: strictfp has been the default since JDK 17 (JEP 306), so floating-point results are now identical on every platform.
Java
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?

Java (and C# classes, Python, JS, Kotlin) stack frame int n = 42 Point p → ● Point q → ● heap object header (mark+klass)int x = 1int y = 2 q = p copies the reference: one object, two names p.x = 9 is visible through q Go / Rust / C / C++ / Zig / C# struct stack frame n = 42 p = Point{x:1, y:2} (inline) q = Point{x:1, y:2} (a copy) q = p copies the bytes(Rust moves non-Copy values) p.x = 9 does not affect q Reference semantics need a GC or ownership rules to know when the heap object dies. Values give locality (no pointer chase, no header); copying big values costs.
Value versus reference semantics. Java primitives live in the stack frame; objects live on the heap, and variables hold references. Go, Rust, C, C++, Zig and C# structs store values inline.
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. equals compares content (chapter 35).
  • Boxing: Java generics need objects, so List<Integer> stores a pointer to a separate heap Integer per 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 has nil pointers, maps, slices and interfaces, plus the famous trap that an interface holding a nil pointer is not itself nil.
Go
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:

Java
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
    }
};

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]

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)

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
Java
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 + impl blocks + traits. No implementation inheritance at all.
  • Zig: structs with methods (functions in the struct namespace, called with . sugar). No inheritance, no hidden constructors: init is a convention.
  • C: structs + functions taking a struct pointer; "classes" are a convention (FILE* and fopen/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; }
}

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 */ }
}

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:

  1. Named constants (C, C++ enum class, C#, Go iota): integers with names.
  2. Sum types / tagged unions / algebraic data types (Rust enum, Haskell data, Zig union(enum), Kotlin and Java sealed hierarchies, Scala 3 enum, TypeScript discriminated unions, Swift enum with 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 {}

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).

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:

return codesC errno, -1easy to ignoreno context exceptionsJava C# C++Python Kotlininvisible pathsstack traces error valuesGo (T, error)explicitbut verbosecan be ignored typed resultsRust Result + ?Zig error unionsHaskell Eitherchecked by types let it crashErlang Elixirsupervisorsrestart clean implicit control flow ←→ failure isolated per process Real systems mix: Rust and Go also panic; Erlang uses {ok, V} | {error, R}.
The error-handling spectrum, from implicit control flow (exceptions) to explicit values (Result types and error unions) to process isolation (let it crash).

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 throw IOException, so you see wrapping into UncheckedIOException.
  • They leak implementation details through interface signatures (throws SQLException from a repository interface).
  • Kotlin, Scala, C# and Groovy dropped them. Modern Java style, including Spring, uses unchecked exceptions for most failures (Spring translates SQLException into its unchecked DataAccessException hierarchy).
  • 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 fillInStackTrace or use the constructor with writableStackTrace=false for 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.

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.

Java
@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:

  1. 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).
  2. Annotation processors (JSR 269) run inside javac and 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-opens tricks.)
  3. 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>,
}

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

Java
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;
Text
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 ==

Java
Integer x = 127, y = 127, p = 128, q = 128;
Text
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):

Java
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);
Text
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>:

Text
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)):

Text
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

  1. Change experiment 2's numbers to Long and Short. Which ranges are cached? Then try Integer.valueOf(1000) == Integer.valueOf(1000) with -XX:AutoBoxCacheMax=2000.
  2. Rewrite experiment 3 using Collectors.joining() over an IntStream. How does it compare?
  3. Measure the memory of experiment 4's two collections with jcmd <pid> GC.class_histogram while the program sleeps.
  4. 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; main as 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; BigDecimal for decimal money; long paise for amounts.
  • Equality: == for primitives and identity; equals/hashCode for value equality, which must be consistent (records generate both).
  • Strings: immutable, UTF-16 internally (compact Latin-1 storage when possible), StringBuilder for building, text blocks and formatted.
  • 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 than StringBuilder for 20,000 appends; List<Integer> about 3× slower to sum than int[]; exceptions about 40× cheaper without stack traces.

Pitfalls

  • == on strings and boxed numbers; equals without hashCode.
  • Integer overflow in totals, counters and (int) casts; double for 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.