Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is null in Java memory [duplicate]

Tags:

java

null

If I declare some string variable like

String str = null; 
  • Is there memory allocated for variable str?
  • If allocated, how many bytes will be allocated?
  • If not allocated, how does the JVM know that there is some variable called str been declared?
  • If allocated and if there is null value inside the memory, then what exactly is the representation of null in binary?
like image 315
Divakara SR Avatar asked Nov 30 '11 03:11

Divakara SR


People also ask

What is null in Java memory?

It means that there is no value associated with name . You can also think of it as the absence of data or simply no data. Note: The actual memory value used to denote null is implementation-specific. For example the Java Virtual Machine Specification states at the end of section 2.4. “ Reference Types and Values:”

Is null a memory location?

If you're in a native language (C and C++, for instance), NULL is a pointer with a zero value, and that points to the memory base address. Obviously that's not a valid address, but you "can" dereference it anyway - especially in a system without protected memory, like old MS-DOS or small ones for embedded processors.

Does null consumes any memory?

Yes memory is allocated to null values as well.

Is null a double Java?

Firstly, a Java double cannot be a Java null , and cannot be compared with null . (The double type is a primitive (non-reference) type and primitive types cannot be null .)


1 Answers

When you do something like:

String str = null;

The only thing allocated is a reference to a string (this is analogous to a string-pointer in languages which contain pointer-types). This reference is a 32 or 64 bit variable (depending upon your hardware architecture and Java version) which resides on the stack (probably, depending upon the exact context in which your declaration is placed).

No memory should be allocated for the null itself, because null is not actually a valid object instance. It is simply a placeholder that indicates that the object reference is not currently referring to an object. Probably it is simply the literal value 0, such that assigning an object reference to null is equivalent to setting a pointer type to NULL in C/C++. But that last bit is conjecture on my part.

like image 119
aroth Avatar answered Sep 28 '22 05:09

aroth