- each call
new Test() creates a new object instance of the
test = new Test(); assigns a reference of that object to variable
- A repeated statement
test = new Test() creates a second instance of
Test and assigns the reference it to the variable
test again, so the first reference is replaced.
If and when the first instantiation will be disposed, however, depends. The Java runtime environment traces references, so as long as there are any references to an object in use, the object won't be disposed. For example, if between step 2 and step 3 the reference to the first instantiation is stored somewhere else (like
Test test2 = test;), and that variable is still in scope when step 3 occurs, then the first object is not disposed, since
test2 is still holding a reference to it. However, when there is no such statement and step 3 omits the one-and-only reference to the first object, then a dispose of that object will happen.
Note that the dispose itself does not happen immediately, but sometimes later, the next time when the garbage collector is run. But that is independent from the semantics of the code discussed, thats only a question of memory and performance.