-4

In C++ , if we create our own constructor then we need to require to deallocate the memory of the object created during construction call.(Correct me if i am wrong)

i want to know about JAVA constructor call. for java also do we require to deallocate memory of the object created or it will deallocate by their own if the object is not in use

2 Answers2

3

In the Java, dynamic allocation of objects is achieved using the new operator.

An object once created uses some memory and the memory remains allocated till there are references for the use of the object. When there are no references for an object, it is assumed to be no longer needed and the memory occupied by the object can be reclaimed.There is no explicit need to destroy an object as java handles the de-allocation automatically. The technique that accomplishes this is known as Garbage Collection.

In Java,Garbage collection happens automatically during the lifetime of a java program, eliminating the need to de-allocate memory and avoiding memory leaks.

To read more visit.

Ankur Lathi
  • 7,636
  • 5
  • 37
  • 49
  • then what is the use of finalize or finalizer?? – Nitish Sajwan Aug 10 '13 at 12:34
  • see my comment to your earlier copy of this question. – LhasaDad Aug 10 '13 at 13:27
  • finalize() is a special method which is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc. Main issue with finalize method in java is its not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called. – Ankur Lathi Aug 10 '13 at 16:06
1

In C++ , if we create our own constructor then we need to require to deallocate the memory of the object created during construction call.(Correct me if i am wrong)

CORRECT!

i want to know about JAVA constructor call. for java also do we require to deallocate memory of the object created or it will deallocate by their own if the object is not in use

Java uses constructors to create objects but there is no concept of desctructors in Java. Because Java is a garbage collected language and hence destruction of object is taken care by JVM instead of desctructor.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • 1
    then what is the use of finalize or finalizer?? – Nitish Sajwan Aug 10 '13 at 12:26
  • the finalize method is called as garbage collection is about to be run on the object (or there about). some folks try and use it for cleanup but its better to have a dedicated method for that on your objects interface and proactively call it. there are restrictions on what can be done in finalize and it will only get called when the item does get GC-ed. note. anything that holds a reference to an object will keep it from being GC-ed (listener registrations, etc). – LhasaDad Aug 10 '13 at 13:26