Memoryeasy0-2 years
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?
They live in two different regions of memory with two different rules for when something dies. The stack holds a method's locals and where to return to; it's small, one per thread, and a frame dies the instant the method returns — nothing decides that, returning is what kills it. The heap holds everything you create with new; it's shared by every thread, much larger, and something has to actively decide a piece of it is no longer needed. In Java that something is the garbage collector, and it only reclaims an object once nothing can reach it anymore — which can be long after the method that created it has returned, if something else (a field, a list, a caller) still holds a reference.
PreviousYou 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?Next Someone writes a 'find the second-largest number' function by sorting the whole list and reading off the second element. It works, it passes every test with a small array, and it's noticeably slow once the list has a million entries. What's actually wrong with the approach, and separately — what's the general mistake in assuming the machine will 'figure out' what you meant for an input you didn't think about, like an empty list?