Object methods stored in stack or heap?

Viewed 1341

What happens to the methods inside the objects of the heap?

So I have been reading about stack and heap memory management.

  • Methods and variables(inside methods) are stored in the stack.
  • Objects and Instance variables are stored inside the heap.
  • When an object is called inside a stack method it has a pointer to the heap object.

I would assume these methods are stored on the stack, because 'methods are stored on the stack'. But I am unable to find confirmation about this. What happens to for example the constructor?

Articles or tutorial video's I have seen only give examples of methods in the main class.

Anyone able to answer this question?

1 Answers

Will explain based on how it works in Java.

Methods and variables(inside methods) are stored in the stack.

Local variables (variables inside methods) are stored in the stack. But not the method itself.

By method, we refer to the behaviour or the list of instructions that needs to be executed. This does not vary every method call and not even vary for every object instance created. The behaviour remains the same at the class level.

The behaviour is stored in a region called Method area. You can refer Java Spec for more details.

As per spec,

The method area is created on virtual machine start-up. Although the method area is logically part of the heap, simple implementations may choose not to either garbage collect or compact it. This version of the Java Virtual Machine specification does not mandate the location of the method area or the policies used to manage compiled code.

It is left to the JVM implementation on where the method area is located.
Implementations like HotSpot VM, until Java 7, used to store the method area as part of the heap. But from Java 8, it is moved out of heap and the space allocated for heap is not consumed by the method area.

What happens to for example the constructor?

Constructions are methods with a special name called, <init>.1. They are stored in the same way as other methods.
As a side note, there is a class initialization method, called <clint>, which handles static block in class.2

Related