0
Test t1 = new Test();
Test t2 = t1;
t1 = null;

What will happen to t2? Will the object be garbage collect?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Yingjie Tang
  • 261
  • 3
  • 3

2 Answers2

4

What happen if I set t1=null while t2 is assigned to t1

The confusion is right there in the title: t2 is not assigned to t1. This line:

Test t2 = t1;

copies the value that's in t1 into t2. There is no ongoing link (other than that they have the same value, which in this case is a thing called an object reference that tells the JVM where to find an object in memory).

I like some ASCII-art when dealing with these kinds of questions:

The line

Test t1 = new Test();

gives us this in memory:

+----------+
| t1       |---+
+----------+   |   +-------------+
               +-->| Test object |
                   +-------------+

Then the line:

Test t2 = t1;

gives us this:

+----------+
| t1       |---+
+----------+   |   +-------------+
               +-->| Test object |
+----------+   |   +-------------+
| t2       |---+
+----------+       

then

t1 = null;

gives us:

+----------+
| t1: null |
+----------+       +-------------+
               +-->| Test object |
+----------+   |   +-------------+
| t2       |---+   
+----------+       

t2 is completely unaffected by antyhing you do to t1.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Nothing happens to t2. It still refers to the same Test instance that was originally referred by both t1 and t2, and as long as that reference exists, this instance can't be garbage collected.

Eran
  • 387,369
  • 54
  • 702
  • 768