简体   繁体   中英

What really happens when an uninitialized instance variable is initialized?

When I declare an instance variable, such as:

BSTNode node;

I know that node is now null, since the instance variable is not initialized. But is some memory allocated to store the value of null , and is node now a reference to that location?

I tried using

System.out.println(node);

Hoping that I would see the address of the reference, but just saw "null" printed out. Why do I not see an address?

Instance variables are initialized to their default values, if the code doesn't explicitly initialize them. All reference variables are initialized to null , per JLS Section 4.12.5 :

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):

...

For all reference types (§4.3), the default value is null.

When a null is passed to System.out.println , the string literal "null" is outputted. The Javadocs for println defer to the print method to cover what happens when a null is passed:

If the argument is null then the string "null" is printed.

There is no address because there is no object yet.

Yes, memory is allocated and a value assigned no matter the initialization.

There is no such thing as "uninitialized": there's explicitly initialized, or initialized with the default value.

Java has no pointers like C/C++. You will never See the memory pointer where you object is located. And if you would get it, it might even chance as garbage collection might move it.

If you print an object, it is made a string calling toString().

"Is node now a reference to that location?"

How is null represented in the memory?

That is implementation specific, and you won't be able to see the representation of null in a pure Java program. (But null is represented as a zero machine address / pointer in most if not all Java implementations.)

There is already a very detailed answer to this question in Stackoverflow: You should check it out!

Also watch this video by Tony Hoare, "Null References: The Billion Dollar Mistake" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM