I've been learning Java for almost a year, but still feel confused when it comes to dynamic memory allocation.
Question 1: Can anyone elaborate what happens in memory when below code get executed based on the steps I wrote (Please correct me if I was wrong)? The more detailed the better.
Question 2: What kind of book/website should I read/visit if I want to dig deeper into JVM or Java memory?
class Student {
private static int counter;
private String name;
private int age;
private String grade = "grade 1";
Student(String _name, int _age) {
this.name = _name;
this.age = _age;
}
public static void main(String[] args){
Student s = new Student("Emma", 6);
}
}
Student.class
file get loaded, static variablecounter
are initialized on data area.main()
get called, JVM allocates memory on stack for local variables
.- JVM allocates storage for member variables
name
,age
andgrade
on heap, and zeros the storage. grade
get initialized as"grade 1"
.- constructor
Student()
get called to initialize the new instance: JVM allocates memory for_name
and_age
on stack, initialize them to"Emma"
and6
, then copy their values to member variablesname
andage
. - JVM assign this new instance to
s
.
You have 4 and 5 out of order. Constructors first call super()
in one form or another, then all initializers and anonymous init blocks, in textual order, then their own body after thesuper()
call if any. You also have the allocation and initialization of _name
and _age
in the wrong place: it happens before the constructor is called. See the JLS and JVM Specification for details.