Skip to content
Advertisement

Instance created inside of a Method

I have not been able to find any reliable literature on this but i’m curious as to where an object is stored if its created inside of a method ? on the stack or on the heap in java 8?

public class A {}
.
.
.
public class B { 
  public void test(){
   A m = new A();
  }
}

I know that normally only local primitives, reference variables and function calls are stored on the stack and that objects are stored in the heap

So I’m assuming that one of the following two scenarios is true either

  • Case 1 : Objects instantiated in a method are as usual stored in the heap with a reference to that object in the stack then when the function finishes the object reference goes out of scope and the object in the heap is then available for garbage collection
  • Case 2 : Objects instantiated in a method are stored in the stack then are available for garbage collection when function finishes

I strongly suspect its case 1, it wouldn’t make sense to store an object in a stack, the only reason I have doubts is because ive come across some literature saying on the stack and others on the heap

Thanks for your feedback ahead of time

Advertisement

Answer

The local reference variable is on the stack, and the object is in the heap.

Note that your question title,

Instance declared inside of a Method

is misleading since objects/instances are declared nowhere — only variables are, and the object created in a method can be placed on fields into a collection, or anywhere it’s needed. And so there is no guarantee that the object should be GC’d when the method exits.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement