Reputation: 11
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
.name
,age
andgrade
on heap, and zeros the storage.grade
get initialized as"grade 1"
.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
.s
.Upvotes: 1
Views: 1574
Reputation: 533790
Some notes;
On newer versions of Java, there is no guarantee that a static field will be initialised if it is never used.
Space for an object is initialised all at once, not on a per field basis. The whole object is zero-ed out (except for the header) not just where the fields are held. i.e. the object has padding it is zeroed out, and it is no slower to zero out eight byte fields than a single long field.
The constructor is called before any field in an object is assigned a value no matter how the code is written.
The first time a String literal is used the String and the underlying char[] or byte[] is also created. grade
is initialised to a reference to that object.
As @biziclop points out it is possible (not just in theory) that none of these things will happen as the whole code can be optimised to nothing (and the JIT can do this today) The only thing which it doesn't do is prevent the String literal from being created as it this happens long before the code has warmed up enough to determine the code doesn't do anything.
Note: with an AOT coming to Java 9, it is possible the code will be reduced to a NO-OP.
Upvotes: 0
Reputation: 311023
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.
Upvotes: 2