Can anybody explain to me how objects are stored and removed from heap memory of Java. I’m looking for more information than simply:
an
Objectwill removed when there is no reference
For example:
class Heap
{
void add(int a, int b)
{
System.out.println(a+b);
}
public static void main(String ar[])
{
Heap obj=new Heap();
obj.add(4,3);
obj.add(5,5);
}
}
Here how is obj and a, `bJ allocated in java memory. When will it be removed from memory by the JVM?
Put simply:
objis allocated on the heap whennew Heap()is invoked.aandbboth are allocated on the stack (primitive types, method arguments), the memory will be released upon returning fromadd.objwill be removed from the heap whenever the garbage collector runs after the execution is out ofmain(the specification does not guarantee the GC will at any given time, it’ll figure out when’s the right time on its own, although almost-full-heap is probably a very common trigger) – in this case though, since the program would terminate, it would be immediately after returning frommain.