0

suppose i have a code snippet like this:-

class A {
   void help() {
      Help helper = new Help();
   }
}

in the above case, the object reference helper will be allocated memory in the stack.

now if i have a case like this

class A {
    Help helper = new Help();
}

in this case, helper will not be allocated memory inside of a stack frame(I am sure of that). will it behave like an instance variable and will be allocated space inside of an object on heap.

Varun
  • 542
  • 1
  • 7
  • 17
  • 4
    Possible duplicate of [Where is allocated variable reference, in stack or in the heap?](http://stackoverflow.com/questions/873792/where-is-allocated-variable-reference-in-stack-or-in-the-heap) – Andy Turner Jan 25 '16 at 15:24

4 Answers4

0

This type of declaration is only located to your instance. the helper attribute will be assigned each time you instanciate you Class A.

It is definitely an instance variable. it goes in the heap

In order to separate the instance and the variable you can use static attribute. Then it is linked to the class so it goes in the code segment.

RPresle
  • 2,436
  • 3
  • 24
  • 28
0

Yes, You are correct. In the second case, the Help object will behave as an instance variable of the class. When you declare the object inside the function, stack memory is used up (local variables). Whereas for instance variables ,heap memory is used.

Rameshwar Bhaskaran
  • 345
  • 1
  • 4
  • 16
0

There is a difference between object and reference variable. For example:

//Here 'helper' is the reference variable
Helper helper = new Helper ();

Whenever we create any object (new Helper()), it’s always created in the Heap space and it's reference (helper) in the Stack space.

Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method.

(Source: https://www.journaldev.com/4098/java-heap-space-vs-stack-memory#java-stack-memory)

So the two objects are stored in the heap but their two reference variables are stored in different stacks.

enter image description here

Tom
  • 16,842
  • 17
  • 45
  • 54
Wael Sakhri
  • 397
  • 1
  • 8
0

Yes, in the second case the memory will be allocated to object helper as soon as the object of class A will be initialized but in the first case the memory will be allocated on the stack to the function named void help() and will be destroyed as soon as the function ends because helper object is a local variable to this function.

Gagan Gupta
  • 1,189
  • 7
  • 19