Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Interview Question: finalize() method

I was given the following phrase in an interview:

The invocation of an Object's finalize() method is the last thing that happens before an object is garbaged collected.

I had to answer by:

  • True
  • False

I've chosen True but it was wrong. Can you please explain me why ?

like image 218
Andrei Ciobanu Avatar asked Jul 22 '10 08:07

Andrei Ciobanu


People also ask

What is the purpose of finalize () method in java?

Overview. Finalize method in Java is an Object Class method that is used to perform cleanup activity before destroying any object. It is called by Garbage collector before destroying the object from memory. Finalize() method is called by default for every object before its deletion.

What is the purpose of finalize () method?

The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class.

When finalize () method is called in java?

The finalize method is called when an object is about to get garbage collected. That can be at any time after it has become eligible for garbage collection. Note that it's entirely possible that an object never gets garbage collected (and thus finalize is never called).

How many times can finalize method is called?

It is invoked only once during the execution of a program. Following are some notable points about the finalize method. Since this method belongs the Object class, which is the super class of all the classes in java, you can override it from any class.


1 Answers

The order is different:

  1. First the object is collected.
  2. Then the object is finalized.

See http://java.dzone.com/articles/ocajp-7-object-lifecycle-java

Object lifecycle:

  1. Created
  2. In use (strongly reachable)
  3. Invisible
  4. Unreachable
  5. Collected
  6. Finalized
  7. Deallocated
like image 186
Daniel Rikowski Avatar answered Sep 21 '22 04:09

Daniel Rikowski