Are methods allocated memory in java ? if so where and when? My teacher said it is given memory when objects are created but then if methods live on the heap how can local variables which are defined in method live on the stack? please clarify in as much details as possible.
Any good book detailing memory allocations for different class members? please recommend.
A method consists of Java byte code. It's the same for each instance of the class. There's no need to create a separate copy of the byte code for each object. No memory needs to be allocated for the code of methods when you create a new object. An object on the heap consists of a block of memory that's large enough to contain the object's non-static member variables (plus some stuff that the JVM needs to keep track of the object).
For local variables that are used in a method, the stack is used at the moment you call the method. Have a look at: Call stack.
Section 2.17.6 of the Java Language Specification says:
Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden. If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError. Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values (§2.5.1).
I have gone to look for myself. If I should return before I get back, keep me here with this tiny ad:
Rocket Oven Kickstarter - from the trailbosshttps://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss