Platformhard5-8 years
Given a subclass `B extends A`, both with static initializer blocks that print, and a program that never mentions `B` until the very last line where it reads `B.name` — why does `A`'s static initializer definitely run before `B`'s, and why does neither run at program start?
Because Java loads and initializes classes lazily, on first active use — a class just sits on disk as bytecode, completely unnoticed, until something actually needs it — and B isn't touched by anything until the very last line reads B.name, so neither A nor B runs its static block any earlier than that. And once that trigger fires, A is guaranteed to finish initializing first, always, even though nothing in the code explicitly asks for A — because a subclass can never be left in a state where it exists but its inherited (superclass) part doesn't. The JVM initializes the whole inheritance chain outward-in: Object, then every superclass down to the one actually being touched, before that class's own static block runs.
PreviousJackson's `ObjectMapper.readValue(json, Order.class)` successfully returns an `Order` object even though the JSON was missing a field the code assumes is always present, and three methods later something throws a `NullPointerException`. Why didn't `readValue` reject the malformed JSON, and how does Jackson actually turn text into an object in the first place?Next A JVM microbenchmark that calls a method once and times it with `System.nanoTime()` reports the method as slow; the same method is fast once the service has been handling real traffic for a minute. What's actually different between those two measurements, and why does HotSpot not just compile everything to machine code immediately at startup?
You get three different Java errors on three different days: `error: illegal start of type`, `Error: Could not find or load main class Foo`, and `Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5`. How do you tell, from the shape of the message alone, what kind of problem each one is — and why can the compiler never catch the third one?A JVM microbenchmark that calls a method once and times it with `System.nanoTime()` reports the method as slow; the same method is fast once the service has been handling real traffic for a minute. What's actually different between those two measurements, and why does HotSpot not just compile everything to machine code immediately at startup?