Java Object Memory Allocation – Instance Fields vs Methods

javajvmmemoryobject-oriented

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

Best Answer

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

Related Topic