The case is, in c++, when you want to create a dynamic object, one that survive more than the block scope on where it is created, you have to do a new and you will receive a pointer.
The new operator in C++ allocates space on the heap. The heap is where the larger part of the main memory is. If you do this, you are responsible for freeing that space when you're done with it using the free operator.
Otherwise, if you just want to use this object in the block scope, you don't need to create it using new...
When you declare variables in C++, memory is allocated on the stack. The stack is where local data is stored and everything you push(add) on it while executing a function will be automatically popped (removed) when the function returns. The stack is usually a lot smaller than the heap, but there are advantages to using it: you don't need to worry about memory management, it is faster, etc.
But in Java, you always have to create them using new, because if not, the object is null and you can use it.
When you declare variables in Java, they are again stored on the stack
As you know, you don't call new on primitive data types (e.g. int i = new int(3);
). When you do something like Object x;
you declare that x
would be a reference to an object of type Object
. However, you do not assign a value to it, so the reference is null (not the object, because there isn't one).
The new operator in Java, roughly speaking, allocates space on the heap, calls the constructor of the object that it is invoked on, and returns a reference to the constructed object. The difference with C++ is that you don't need to free the object yourself - there is a garbage collector. In essence, what it does is that it monitors how many references point to an object, and if they go down to zero it deletes the object automatically.
So when you do
Object y = new Object();
x = y;
you will get two references (x and y) pointing to the same object. When you have a function call like this
Object foo() {
Object y = new Object();
return y;
}
void bar() {
Object x = foo();
...
}
in the
...
part of
bar()
you would have the reference
x
, pointing to the object created in
foo()
. Since
foo
has returned, the
y
reference has been freed, thus there would be only one reference to this object in the
...
part of the program. If you don't copy the
x
reference anywhere in
bar
and
bar
returns, then there would be 0 references to the object, and the garbage collector would
collect it (although not immediately).
-Stan