Reputation: 99
If I set an object with a null
value does Java destroy the original object?
For example:
Foo f = new Foo();
// ...
Foo b = f;
If I now set b
to null
does f
become also null
? What is the generic name for this behavior?
Upvotes: 3
Views: 132
Reputation: 1075615
No. All setting b
to null
does is remove the reference to the object from b
. f
will still have a reference to the object. If you also set f
to null
, then the object will have no outstanding references, and will eventually be garbage collected.
Let's throw some ASCII-art at this:
First we do this:
Foo f = new Foo();
and get this in memory:
+------------+ | f | +------------+ +-----------------------+ | (Ref #123) |---->| Foo #123 | +------------+ +-----------------------+ | (data for the object) | +-----------------------+
(Obviously, that #123 is just there to give the idea that the ref does have some specific value; we never see that actual value, but the JVM does.)
Then if we do this:
Foo b = f;
we have:
+------------+ | f | +------------+ | (Ref #123) |--+ +------------+ | | | +-----------------------+ +->| Foo #123 | +------------+ | +-----------------------+ | b | | | (data for the object) | +------------+ | +-----------------------+ | (Ref #123) |--+ +------------+
Then if we do
b = null;
we have:
+------------+ | f | +------------+ +-----------------------+ | (Ref #123) |---->| Foo #123 | +------------+ +-----------------------+ | (data for the object) | +------------+ +-----------------------+ | b | +------------+ | null | +------------+
As you can see, f
and the object itself are not affected.
Upvotes: 12
Reputation: 4135
Short Answer: No. The original reference will remain intact regardless of what happens to other references to the same object.
Long Answer: When you create a variable (let's call it A), strictly speaking you are creating a reference. When you assign a value to the object the system creates the object in question, and stores a reference to it in the variable. If you create a second variable and assign it the same value, you are creating a second reference to the same object. Although the underlying object is the same in both cases, the references are different, and can be manipulated separately. When you assign a value to a pre-existing variable, what you are actually doing is changing the location the reference points to. However you are not actually changing the object itself. In the case no assigning null what you are actually telling the computer is "this reference points nowhere".
Other references however are not effected by this change, and still point to the same place. The object is not effected at all by changing the assignment, so long as it is still referenced in at least one location. If it is referenced nowhere - and is thus unreachable - it will be garbage-collected by the system, and be destroyed.
Upvotes: 1