13

I have a following class

class Student{

int rollNumber;
int marks;

public void setResult(int rollNumber, int marks){

    this.rollNumber=rollNumber;
    this.marks=marks;   
}

public void displayResult(){

    System.out.println("Roll Number= "+this.rollNumber+"   Marks= "+this.marks);

}
}

Now I create two objects of type Student as follows

Student s1=new Student();
Student s2=new Student();

Now two different sets of memory is allocated for instance fields. Now my question is whether memory is allocated for methods (setResult and displayResult) twice or once?

Please see the following figure and can you help me saying which figure gives correct information.

enter image description here

  • 1
    Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask – gnat Sep 18 '14 at 17:09
  • 3
    I'am learning java...and in all the materials they just say that whenever we create an object a fresh memory is allocated to all the instance fields..but, none of the materials said whether fresh memory will be allocated for methods or not – Harish_N Sep 18 '14 at 17:20
12

The code for methods is part of the Class (more concisely, Class<Student>) and it is loaded into memory when the class is first loaded.

That said, when you execute any method additional memory is used, to allocate memory to parameters, local variables, temporary expression results, return values and so on. But such memory is allocated in the stack (the memory used when creating a new instance is allocated in the heap.

As per your question, it should be clear now that figure B is correct (although it does not reflect what happens when you actually call the method).

  • Ok. I'am 90% clear now....But a small doubt.. Suppose if i create a 10 objects of type Student then only 1 set of fresh memory is allocated to the methods present in class Student whereas 10 sets of fresh memory is allocated to store instance variables for 10 objects..Am i right? – Harish_N Sep 18 '14 at 17:08
  • Right. Think that it is not only the properties that take memory, there is a small overhead related to the instance itself (an instance of a class with no properties will use more than 0 bytes of memory). – SJuan76 Sep 18 '14 at 17:15
  • One more thing... I asked question keeping java in mind....Does the same thing happens in java..... – Harish_N Sep 18 '14 at 17:18
  • The Java Language Specification doesn't say anything about how much memory is allocated when and for what purpose. That is left to the implementer, and every implementer may choose differently. – Jörg W Mittag Sep 18 '14 at 19:40
6

Instance fields (including property backing fields) get N-copies for N-objects.

Static fields get a single copy per class.

Methods are blocks of bytecode (or after JIT, blocks of native instructions) that are part of the program "image" or executable code segment. Methods are already part of the program image as it sits on disk. Once the image is loaded by the OS (or CLR), there is a single shared copy of the method code.

They aren't part of "heap" or runtime allocation in general, except in cases where you may use the hostable compiler to compile new methods on the fly. Methods don't get "allocated" like objects and they aren't "allocated" relative to the object creation. They merely exist as part of the program before a single object is ever instantiated. Even lambdas / delegates aren't allocated on the fly. The compiler creates classes on-demand to implement these other seemingly dynamic code objects, and they also exist as part of the bytecode image on disk.

UPDATES per comments:

The JVM standard has this to say:

2.5.4. Method Area

The Java Virtual Machine has a method area that is shared among all Java Virtual Machine threads. The method area is analogous to the storage area for compiled code of a conventional language or analogous to the "text" segment in an operating system process. It stores per-class structures such as the run-time constant pool, field and method data, and the code for methods and constructors, including the special methods (§2.9) used in class and instance initialization and interface initialization.

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. The method area may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger method area becomes unnecessary. The memory for the method area does not need to be contiguous.

So it is clear that (1) yes the spec does not dictate how this is done, but (2) it is analogous to the storage area for compiled code of a conventional language, ie. the text segment. This is the point I'm making.

  • What you are saying makes sense, but is that actually guaranteed by the JLS? Normally, the JLS gives implementors a lot of leeway in questions like this. – Jörg W Mittag Sep 18 '14 at 19:42
  • Not sure on that point, @JörgWMittag. You may be right. The point I tried to make is "new T()" doesn't allocate a new instance of a method. As to the specifics of the JVM, classloaders do indeed store bytecode in the heap, and I guess there are possible scenarios where classes themselves are instantiated and even garbage collected. But it is implementation detail of the runtime, and conceptually, the heap I'm talking about is the "user" heap. The class & methods are not considered data in the normal user context. But since we can also control a classloader from userland, I guess I don't know. – codenheim Sep 18 '14 at 19:53
  • The JLS doesn't even talk about a heap at all, doesn't it? It's perfectly legal to implement Java with a dynamic stack and no heap instead of a finite fixed-size stack and a dynamic heap. The JLS also doesn't say anything about the JVM, it's perfectly valid to implement Java without a JVM. – Jörg W Mittag Sep 18 '14 at 19:56
  • You are referencing JLS, but I'm talking JVM. The JVM standard certainly discusses heap. You must provide a variable scope/lifetime that escapes the local scope of the stack. As to what is theoretically possible, I prefer to think in terms of "known implementations". I'm pretty sure implementing a full JVM without a heap primitive is a tough, or even impossible, job since the JVM isn't a pure stack machine. My understanding of the Forth machines, and other pure stack architectures, are that it may be possible if a primitive exists for random variable access, but I just haven't seen it. – codenheim Sep 18 '14 at 20:15
  • @JörgWMittag - I added to the answer something that may be of interest for our discussion. The point is I was drawing an analogy to the traditional code or text segment in conventional runtime systems. – codenheim Sep 18 '14 at 20:18
-4

object allocated in heap memory.when object are allocated the slot for all the instance variable is created and destroyed when the object are destroyed.so instance variable is also allocated in heap memory.And the local variable are created in stack at the time when the method are called.

  • 1
    This appears to just repeat information that is provided in earlier answers. – user40980 Feb 17 '16 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.