Platformeasy0-2 years
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?
Each error names the stage it happened at, and the stage tells you where to look. A compile error (illegal start of type) means the text you wrote isn't legal Java — nothing was produced, so look at the file and the line. A startup error (Could not find or load main class) means the source compiled fine but the runtime can't find what you're asking it to run — look at where things are (the classpath, the directory, the class name), not at your logic. A runtime error (a stack trace) means it compiled, it loaded, and it ran — and the values were wrong. The compiler can't catch that last kind because x[5] on a two-element array is perfectly legal Java; the array's actual size isn't known until the program runs.
PreviousA beginner writes `x = y; y = x;` expecting to swap two variables, and it does not work. What actually happens, and why does `=` behave this way instead of the way algebra taught them?Next A method's local variable disappears the instant the method returns, but an object created inside that same method can still be alive minutes later. Why do these two things, created in the same line of code, have such different lifetimes?
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?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?