if we assign null to any object what it actually is it some memory location in heap OR anything else.
One should distinguish reference
and object
. You can assign null
to a reference.
Objects are normally created in heap using new
operator. It returns you a reference to an object.
A a = new A();
object with type A
is created in heap. You are given back reference a
. If now you assign
a = null;
the object itself still reside in heap, but you would not be able to access it using reference a
.
Note that object might be garbage collected later.
UPD:
I have created this class to see byte code of it (first time to me):
public class NullTest {
public static void main (String[] args) {
Object o = new Object();
o = null;
o.notifyAll();
}
}
And it produces:
C:\Users\Nikolay\workspace\TestNull\bin>javap -c NullTest.class
Compiled from "NullTest.java"
public class NullTest {
public NullTest();
Code:
0: aload_0
1: invokespecial #8 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: new #3 // class java/lang/Object
3: dup
4: invokespecial #8 // Method java/lang/Object."<init>":()V
7: astore_1
8: aconst_null
9: astore_1
10: aload_1
11: invokevirtual #16 // Method java/lang/Object.notifyAll:()V
14: return
}
You can see that set null to a reference results:
8: aconst_null
9: astore_1
List of byte code instructions
Basically it puts value of null to the top of stack and then saves to the reference. But this mechanism and reference implementation is internal to JVM.
How is reference to java object is implemented?