Let's start with the following simple statement:
String x = null;
What does this line of code do? Let's first think about what is variable and value ). We usually compare a variable to a box. We can use a box to hold things. Similarly, we can use variables to change the storage value. When defining a variable, you must specify the variable type.
In Java, there are two main data types: Basic Data Type and reference type. Variables defined as basic data types are used to save values, while variables defined as referenced variables are used to save references. So what the above Code does is declare a variable x to store references. Here, x does not reference any objects.
The following figure shows the situation more clearly:
If x = "abc", the situation is as follows:
What is null in memory? First, null is not a legal object reference, so the system does not allocate memory to it. It is only a value that indicates that the referenced variable does not reference any object.
The JVM specification says this:
The Java virtual machine specification does not specify the value of null.
Therefore, the number of null depends on the JVM implementation vendor. It may be an integer 0, just like the C language.
What is x in memory? Now we know what null is. A variable is actually a storage address with a name (identifier) that can be used to store some values. So where is x in the memory? In Java, the method is placed in the stack of the memory space of the current thread, and each method is placed in a frame of the stack. Therefore, x is stored in the frame of the method.
Original article: http://www.programcreek.com/2013/12/what-exactly-is-null-in-java/