Reputation: 369
My teacher gave me a question:
"What occurs when objects are created in Java".
To the best of my knowledge, memory allocation, variable initialization and constructor method invocation happen when an object is created.
But my teacher said that I was almost right. The 2 later things are right, except memory heap. Instead, he said the memory allocation occurs. I think that object is stored in heap, so my teacher is wrong. Do you think so?
Upvotes: 9
Views: 21081
Reputation: 21
When object is created in java then these 6 step will be happens one by one--- 1.JVM allocates 8 bytes of memory for the reference variable & assign default value as null.
Upvotes: 2
Reputation: 4844
On top of what other people have said, if this is the first use of the object then its Class must be initialised -as described in the JLS (the section before the one on new instance creation!).
This basically involves loading into memory the necessary information about the class i.e. creating a Klass
object for the static variables and method table to live. This may also involve loading super classes and interfaces. This is all carried out by the ClassLoader
.
Upvotes: 2
Reputation: 26868
As always, the best place to find a solution for these kinds of questions is in the Java Language Specification.
Specifically, from the section on new instance creation, it can be understood that this is the sequence when a new object is created, as long as no exceptions occur:
Object
. By first line I mean either explicit call to super()
or this()
, or an implicit call to super()
.Now, it is possible that your teacher is talking about memory allocation as an actual operating system call - and in that case he's right in the sense that the JVM manages its own heap and thus a Java memory allocation does not necessarily translate to an OS memory allocation call (although it may).
Upvotes: 15
Reputation: 2741
While the JVM is running the program, whenever a new object is created, the JVM reserves as portion of the Heap for that object (where the object will be stored). The amount of Heap that gets reserved is based on the size of the object.
The JVM maps out this segment in the Heap to represent all of the attributes of the object being stored. A reference (address in Heap) to the object is kept by the JVM and stored in a table that allows the JVM to keep track of all the objects that have been allocated on the Heap. The JVM uses these references to access the objects later (when the program accesses the object).
Upvotes: 2
Reputation: 95958
I'll answer that using a simple example.
Say you have a class Car
. Now you write:
Car car;
car = new Car();
The first statement creates a reference with car
in the stack.
In the second statement, the Car
class will be loaded to the main memory, then it will allocate memory for the members of Car
in the heap. When this happens, the members will be initialized with values provided by the JVM.
Upvotes: 3