Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

memory allocation for methods in java.  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Mani Tiwary
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please reply
 
Java Cowboy
Sheriff
Posts: 16083
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Methods do not live on the heap.

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).

 
Ranch Hand
Posts: 84
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you could check this link out, http://bittermanandy.wordpress.com/2008/10/19/garbage-part-one-stack-and-heap/
 
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 trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!