You are only manipulating the local variable l
in your method createMap
. The variable map
in your first method is still pointing to null.
To understand how this works, consider this:
In your main
method, you are creating a varialbe map
, and assigning it null. You now have this variable on your stack, but still no corresponding object on the heap.
You then pass this variable as a parameter to createMap
. Java does this call by value
, i.e. it makes a copy of the variable and pushes it to stack in conjunction with the method call. You now have two variables on the stack, and still no object on the heap.
Finally, inside your createMap
method, you create a new Map object and assign it to l
, your copy of the first variable. Now, you have two variables on the stack, and one object on the heap, of which one points to the Map object:
map ---> null
l ---> Map
When the createMap
method returns, the stack is popped and your variable l
is deallocated. map is still not pointing to the Map object - it never did, it will still point to null. Further, since the Map object now has no live references, it will be swept up by the next garbage collection cycle.
So, what you have in the end is again a single variable on the stack, which still points to null.