I know that when declaring object instances in c++ like so:
Object object
the Object constructor is called and memory is provided for that object, however i find that when you do this in java the object instance doesn't have a value until:
object = new Object()
is written. I want to know specifically when memory is provided for the object. I thought that both construction and the new keyword allocated memory so Object object = new Object()
seems redundant. I read on oracle's site that declaration "reserves" memory and new "allocates" memory, I would like to know what is the difference between the two.
You need to differentiate between the space required for the variable and the space required for the object. Bear in mind that the value of the variable is just a reference - very much like a pointer in C++. So if you have:
Object x = null;
then the variable x
itself takes up enough space for a reference (usually 4 or 8 bytes). Now if you have:
x = new Object();
that creates an object - the value of x
is now a reference to the newly created object. x
itself takes up the same amount of space as before, but there's also the space required for the object itself (basically the fields, a reference for the type of the object, and data for synchronization and house-keeping).
See more on this question at Stackoverflow