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

Workbench / Volume 3 Companion: The Backend

V3·33

Language Foundations

Companion to Volume 3, chapter 33: how Java's types, values, equality, strings, records and errors connect, compared with C, Go, Rust and Python; new angles (a primitive as a fixed-size box, a reference as a house address, Integer's cache as a coat check); what the chapter simplifies, measured on JDK 21 and the build's stage 34: number parsing that accepts digits from every script, default locales that change digits and letters, and a linter whose 17 findings on careful code were all intended; the theory behind two's complement and IEEE 754; how OpenJDK's Integer.parseInt accumulates negatively and why; four debugging drills; interview questions with how to approach each.

6 sections · ~11 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 33 has six parts: syntax and program structure, types and values (primitives, integer overflow, floating point, reference and value types, operators and equality, control flow), data (arrays and strings), behaviour (methods and parameter passing, classes, interfaces, packages and modules), modelling data (enums and records) and errors (error-handling models and annotations).

values structure failure primitive types fixed width overflow wraps or throws floating point binary fractions money whole paise strings, Unicode locale, digits reference types identity vs value equality ==, equals, hashCode records, enums data as values interfaces, modules visibility parameter passing copies of references error models exceptions, results checked exceptions in the signature try-with-resources always closed annotations metadata, tools compile-time rules plugins, lint so unlike not for shown as needs generated by implement and or with and read by goes deeper: Vol 1 ch2 (memory) · Vol 1 ch5 (number representation) · ch34 OOP · ch36 generics · ch40 JVM · Volume 23 internationalisation exercises: P1–P10 four languages, overflow, BigDecimal, equality, references, Unicode, records, exceptions, sealed types, annotations; C1–C3 money domain, error ports, notifications
Concept map of chapter 33, language foundations compared across languages: syntax and program structure, types and values (primitives, overflow, floating point, reference and value types, operators and equality, control flow), data (arrays, strings), behaviour (methods and parameter passing, classes, interfaces, packages and modules), modelling data (enums, records) and errors (error-handling models, annotations), with links such as fixed-width integers leading to overflow and reference types leading to equality rules.

The links worth remembering:

  • Every value has a representation, and the representation leaks. Fixed-width integers wrap; binary floating point can't hold 0.1; strings are UTF-16 code units, not characters; a reference is an address, not the object. Most of the chapter's pitfalls are a representation showing through an abstraction.
  • Identity and value are different questions. == asks "the same object?" for references and "the same bits?" for primitives; equals asks whatever the class decides. Records, enums and hashCode contracts are all ways of making value equality reliable.
  • Errors are part of a method's type, one way or another. Java's checked exceptions, Go's (T, error), Rust's Result<T, E> and Python's exceptions differ in where the possibility of failure is written down, not in whether it exists.

Explain it differently

1. A primitive is a box of fixed size. An int is a box with 32 slots; pour in more and the top spills away (overflow), leaving what fits. Math.addExact is a box with an alarm.

2. A reference is a house address on a card. Passing it to a method copies the card, not the house: the method can repaint the house (mutate the object) but can't change which house your card names (Java is pass-by-value, and the value is the address).

3. Integer's cache is a coat check with 256 hooks. Values from -128 to 127 always get the same hook, so two tickets for 127 point at the same coat (== is true); 128 gets a fresh coat each time (== is false). equals compares the coats, not the hooks.

4. Floating point is a ruler marked in binary fractions. 0.5 and 0.25 have marks; 0.1 falls between two marks, so the ruler records the nearest one: 0.1000000000000000055511151231257827021181583404541015625.

5. A default locale is a translator you didn't hire. Every String.format without a Locale hands your numbers to whoever the machine's settings appoint; on a server configured for Egypt, 1234 comes back as ١٢٣٤.

6. A record is a labelled envelope. Its contents are fixed when sealed (immutable components), the label lists them (the canonical constructor), and two envelopes with the same contents are equal. The envelope doesn't stop you putting a mutable list inside, though.

7. A checked exception is a warning label the compiler insists on. The method's signature says "may fail like this", and every caller must decide: handle it, or put the same label on itself.

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from OpenJDK 21.0.12 and the build's stage 34 (exp/34), unless stated.

1. "Parse the number" depends on which digits you meant. The chapter's string and number sections use ASCII digits. Java's parsers accept every script's decimal digits:

Terminal
Integer.parseInt("123"  ) = 123                     matches("\\d+") true   matches("[0-9]+") true
Integer.parseInt("١٢٣"  ) = 123                     matches("\\d+") false  matches("[0-9]+") false
Integer.parseInt("१२३"  ) = 123                     matches("\\d+") false  matches("[0-9]+") false
Integer.parseInt("123"  ) = 123                     matches("\\d+") false  matches("[0-9]+") false
Integer.parseInt("+123" ) = 123                     matches("\\d+") false  matches("[0-9]+") false

Arabic-Indic, Devanagari and fullwidth digits all parse as 123, and a leading + is accepted; Java's regex \d means ASCII only (unless UNICODE_CHARACTER_CLASS is on). So a validation regex and the parser can disagree, in either direction. TiffinBox's search limit accepted ٢; harmless there, but anywhere two spellings of one number are treated differently (a cache key built from the raw string, a rate limit counted per string, a log filter), it's a bypass. Validate with the exact set you mean ([0-9]), then parse.

2. Default locales change digits and letters, not just currency symbols. The chapter's string section mentions locales for display. String.format("%d", 1234567) under different defaults:

Terminal
en-IN            \u001f   1234567
hi-IN            \u001f   1234567
ar-EG            \u001f   ١٢٣٤٥٦٧
fa-IR            \u001f   ۱۲۳۴۵۶۷
mr-IN            \u001f   १२३४५६७
bn-BD            \u001f   ১২৩৪৫৬৭
th-TH-u-nu-thai  \u001f   ๑๒๓๔๕๖๗

(The middle column, a %04x escape, stays ASCII: hexadecimal isn't localised.) And case mapping:

Terminal
tıtle TİTLE SS 2

"TITLE".toLowerCase(tr) gives tıtle (dotless ı), "title".toUpperCase(tr) gives TİTLE, and "ß".toUpperCase() is two characters, SS: case mapping can change a string's length. A server whose JSON, logs or keys go through default-locale formatting works in development and breaks on a machine configured for another country. Stage 34's locale rule enforces Locale.ROOT for machine text.

3. Most findings of a good linter on careful code are intended. The chapter recommends tooling. Stage 34's LangLint found 17 places in TiffinBox (12 narrowing casts, 2 broad catches, 1 narrowing in the HTTP parser, 2 formats without a locale), and reading each found no bug: casts after range checks, bit-level casts in a CRC and a varint encoder, last-resort catches. Even an input built to exploit one of them was refused before the cast:

Terminal
42949672.97% -> RuleError: line 1, column 34: a percentage must be between 0.01% and 100%

(42949672.97% is 4,294,967,297 basis points, which would wrap to a valid 1 as an int.) A linter's value isn't only in bugs found today; it's in making intent explicit (Math.toIntExact, a suppression with a reason) so that a future change that removes the check is caught. Teams that measure a linter by "bugs found in week one" switch off useful rules.

Common misconceptions

Misconception What's actually true Where it's shown
"\d and parseInt agree." parseInt reads ١٢٣ as 123; \d doesn't match it. Gaps 1
"Locales only affect currency display." Digits and case mapping change; ß uppercases to two letters. Gaps 2
"Java is pass-by-reference for objects." It passes references by value. Explain it differently 2
"Integer == works for small numbers, so it's fine." 127 == 127 is true, 128 == 128 false: true false true. Code walkthrough experiment
"Math.abs is never negative." Math.abs(Integer.MIN_VALUE) is -2147483648. Code walkthrough
"new BigDecimal(0.1) is exact." It's exactly the double: 0.1000000000000000055511…; use BigDecimal.valueOf. Code walkthrough experiment
"A linter that finds nothing is wasted." It keeps careful code careful. Gaps 3

Theoretical gaps: the ideas behind the chapter

1. Two's complement. An n-bit integer represents −2ⁿ⁻¹ to 2ⁿ⁻¹−1; negation is "invert and add one", so the most negative value is its own negation. That one fact explains Math.abs(MIN_VALUE) < 0 and why parsers accumulate negatively (Code walkthrough).

2. IEEE 754. A double is a sign, an 11-bit exponent and a 52-bit fraction: about 15–17 significant decimal digits, exact for integers up to 2⁵³, never for most decimal fractions. Rounding is to nearest, ties to even; NaN is unequal to itself.

3. Unicode's layers. Code points (U+0000..U+10FFFF), encodings (UTF-8, UTF-16 with surrogate pairs), grapheme clusters (what a reader sees as one character) and normalisation (é as one code point or two). Java's String.length() counts UTF-16 units, the second layer.

4. Value semantics versus reference semantics. Values are equal when their contents are; objects have identity. Languages choose defaults differently: Rust and Go structs are values, Java classes are references, Java records are references with value equality, and Project Valhalla's value classes would give Java true values.

5. Exceptions versus result types. Checked exceptions and Result<T, E> both put failure in the type; unchecked exceptions and Go's convention ((T, error), checked by discipline) don't enforce handling. The trade-off is between local clarity and the friction of propagating.

Applying it

Code walkthrough

Gaps 1 found that parseInt reads any script's digits. Here is why, in OpenJDK's own code: Integer.parseInt(String, int) from the jdk21u repository (src/java.base/share/classes/java/lang/Integer.java).

The sign and the limit

Java
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+') {
                    throw NumberFormatException.forInputString(s, radix);
                }

A leading + is accepted explicitly. The limit is the most negative value the result may reach: -MAX_VALUE for positive numbers, MIN_VALUE for negative ones.

Accumulating negatively

Java
            int multmin = limit / radix;
            int result = 0;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                int digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0 || result < multmin) {
                    throw NumberFormatException.forInputString(s, radix);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s, radix);
                }
                result -= digit;
            }
            return negative ? result : -result;

Two things explain the chapter's gaps. First, Character.digit(ch, radix) is the Unicode-aware lookup: any character with a decimal digit value counts, so ٣ is 3. Second, the result is built as a negative number and negated at the end, because in two's complement the negative range is one larger: -2147483648 can be accumulated, +2147483648 can't. The overflow checks happen before each multiplication and subtraction (result < multmin, result < limit + digit), so the method never relies on wrapping. That's the pattern Math's *Exact methods package up.

Debugging drills

D1. Two "identical" orders

Duplicate-order detection compares quantities with == and misses duplicates for large catering orders, but works for small ones.

D2. JSON breaks on one server only

After moving to a new data centre, some API responses contain "total":١٢٣٤ and clients fail to parse them. The code didn't change.

D3. A discount that wrapped

A rules file with an enormous percentage was accepted and applied a small discount.

D4. A search finds Istanbul's kitchens but not İzmir's

Kitchen search lowercases names and queries. On some developers' machines it matches İzmir, on the server it doesn't.

Career-oriented

Interview prep

Mid-level 1: how would you store money?

Question. "How do you represent money in a Java service?"

How to get there. Why not double, then the options, then rounding and currency.

Mid-level 2: equals and hashCode

Question. "What goes wrong if you override equals but not hashCode?"

How to get there. The contract, then a concrete failure, then how records help.

Senior 1: a production bug from a default

Question. "Tell me about a bug caused by a default setting, and how you'd prevent the whole class of bug."

How to get there. Pick a default (locale, time zone, charset, timeout), the failure, and a mechanism that prevents recurrence.

Senior 2: exceptions or result types?

Question. "Should our new Java service use checked exceptions, unchecked exceptions, or result types for errors?"

How to get there. Separate expected business outcomes from failures, then match each to a mechanism.

Staff 1: raising the language bar across teams

Question. "Twenty teams write Java with very different quality. How would you raise the floor?"

How to get there. Automate what can be automated, teach what can't, and measure.

Staff 2: adopting a new Java version

Question. "We're on Java 17. Should we move to 21, and how?"

How to get there. Benefits, risks, and a rollout plan with checks.