I am trying to understand how null works in Java.
If we assign null to any object, what happens actually behind the scene? Does it assign a memory location address pointing to a null “object” or something else?
I’ve tried the following program and I’ve come to understand that all nulls point to same location.
But can anybody tell me how Java throws NullPointerException and how null works in Java?
class Animal{
}
class Dog{
}
public class testItClass {
public static void main(String args[]){
Animal animal=null;
Dog dog=null;
if(((Object)dog) == ((Object)animal))
System.out.println("Equal");
}
}
Output
Equal.
One should distinguish
referenceandobject. You can assignnullto a reference.Objects are normally created in heap using
newoperator. It returns you a reference to an object.object with type
Ais created in heap. You are given back referencea. If now you assignthe 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):
And it produces:
You can see that set null to a reference results:
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?