What is null in Java?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.