Let's start with this simple statement:
String x =
null
;
What does this line of code do?
Recall what is called a variable (variable) and what is called a value. We usually liken a variable to a box. We can use boxes to load things, and we can use variables to save values. You need to specify the type of the variable when defining the variable.
In Java, there are 2 primary data types: The base data type and the reference type. Variables defined as basic data types are used to hold values, while variables defined as references are used to hold references. So the work of this line of code is to declare a variable x, which is used to store the reference. Here x does not reference any objects.
The following diagram shows a clearer picture of the situation:
If x = "abc", then the situation is as follows:
What exactly is null in memory?
First, NULL is not a valid object reference, so the system does not allocate memory to it. It is simply a value that indicates that the reference variable does not refer to any object.
That's what the JVM spec says:
1 |
Java虚拟机规范并没有强制规定 null 应该是什么值。 |
So, how much is null, depends on the JVM implementation vendor. It could be just like the C language, which is actually an integer 0.
What is x in memory?
Now we already know what a null is. A variable is actually a storage address plus a name (identifier) that can be used to store some values. So where is x exactly in memory? In Java, the method is placed in the stack of the current thread's memory space, and each method is placed in a frame of the stack. So, x is stored in the frame where the method is located.
Original: http://www.programcreek.com/2013/12/what-exactly-is-null-in-java/
What is null in Java?