The question, and especially insisting on that particular “correct” answer of 4, doesn’t make much sense, as it draws several assumptions about how a JVM works which are naïve in the best case or simply wrong.
The first thing it does wrong is to assume to know, how many objects are ever created.
The main
method creates three instances of Icelandic
having an inherited field weight
initialized with the value of 1200L
. The value 1200L
is converted to a Long
instance via auto-boxing using the method Long.valueOf
which is allowed, but not required to cache frequently requested values. So we can’t predict the number of Long
instances created here, it might be one or three, but even two is possible if the caching did not work for all invocations, for whatever reasons.
Then the code is playing around with the local variables holding the three instances and is supposed to hold only one of these instances “after” line 14 but there is no associated code after that line for which this state could have a relevance. The only thing which happens after that line is returning from the main
method so after line 14 all local variables are out-of-scope.
Whether there is a point of execution which can be associated with “after line 14” but still being in method main
where exactly one instance of Icelandic
is in scope depends on whether line debug information have been included in the class file and how the compiler did map byte code instructions to these line numbers.
If the return
byte code instruction inserted by the compiler is not associated with line 15, all instances created in the main
method might be garbage collected after line 14 but keep in mind that the Long
instance might still be referenced from a global cache and hence not be eligible to garbage collection. We simply can’t predict.
There is another aspect of JVM execution: optimization. JVMs are allowed to perform “escape analysis” and elide object creations if they don’t have any impact on the programs semantics. In your program, all objects are unused from a JVMs point of view. So another legal execution scenario is that this main
method never creates any object and then there are no object eligible for garbage collection at all.