Questions of this kind seems to be very popular when teaching Java to beginners, but are complete nonsense. While an answer like this is great for making, whoever invented this question, happy, it’s not correct when digging deeper:
References to objects held in local variables do not prevent objects from being garbage collected. If the subsequent code does not touch them, these object may still be considered unreachable, which is not a theoretical issue. As demonstrated in “finalize() called on strongly reachable object in Java 8”, even the ongoing execution of a method of that object does not hinder its collection, if the instance is not subsequently touched.
Since in your example code, the objects do not hold any data, it’s obvious that they are never touched at all, which implies that they might get collected at any time, depending on the optimization state of the JVM. The code might also get optimized to a degree that it only performs the visible side effect of the two print statements, in other words, that the objects are never created at all.
This is backed by The Java® Language Specification, § 12.6.1. Implementing Finalization:
Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a Java compiler or code generator may choose to set a variable or parameter that will no longer be used to null
to cause the storage for such an object to be potentially reclaimable sooner.
Another example of this occurs if the values in an object's fields are stored in registers. The program may then access the registers instead of the object, and never access the object again. This would imply that the object is garbage. …
Practically, since this is trivial short-running code inside a main
method, the most common scenario would be that the code runs unoptimized, but no garbage collection will ever happen in that short run time.
This leads to the other reason why asking such questions is nonsense. It might be challenging to find the right points when an object is naively considered unreachable, it’ll be impossible to guess when and how the optimizer influences the outcome, but the entire purpose of the garbage collection is that the developer doesn’t have to worry about that.