A null value can only be given to a reference type, and if I understood it right it points to address 0. In addition, if creating an instance of a class using the "new" keyword, we are allocating a memory for an object. My question is if we initialize an object to null, does it still consume memory?
-
Do you mean "initialize *a reference* to null"? If you're not creating the object, it won't use up any memory (apart from a few bytes for the reference itself). – Steve Smith May 14 '19 at 13:18
-
1Just because your car isn't parked in your garage, that doesn't mean that your garage takes up no space. – Andy Turner May 14 '19 at 13:19
-
2@AndyTurner I wouldn't make that analogy, I think comparing references to towing hitches is more apt. A car has to be smaller than a garage. A towing hitch can be small but tow a huge load. References are small, but can point to large objects. – zero298 May 14 '19 at 13:21
2 Answers
int[] arr = null;
Doesn't actually initialize anything. It just creates a reference arr
which will point at the address 0. So no, it will not take any space, except for how much the reference arr
itself takes (usually 4 or 8 bytes depending on the system).
This on the other hand does initialize the object and will take "a lot" of space (at least the size of 10x int
, so >= 40 bytes):
int[] arr = new int[10];

- 21,987
- 6
- 62
- 97
I have two interpretations of what you are trying to say:
Initializing as NULL
String hello = null;
This doesn't even initialize anything. It's like having a drawer, putting a label on it, but not actually putting anything inside of the drawer. As a result, it does not consume any memory
Setting to NULL
String hello = "hey there!";
hello = null;
This is like having a drawer full of stuff, then taking all that stuff out and throwing it away. This is still consuming memory, as the old stuff you threw away is still existing. In order to get rid of the old stuff, garbage collection will usually kick in sooner or later and remove all of it. You could also System.gc()
manually, not that I recommend it.

- 1,150
- 12
- 25
-
2
-
1[`System.gc()`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/System.html#gc()): "Calling the `gc` method **suggests** that the Java Virtual Machine ..." means that it is not guaranteed that any garbage collection is performed at all. – Gerold Broser Oct 19 '19 at 00:12