File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes GC question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "GC question" Watch "GC question" New topic

GC question

Surendra Kumar
Ranch Hand

Joined: Jul 04, 2006
Posts: 236
The below program compiles and runs.
But my doubt is that the finalize() method should be 'protected', right?
so, how come this version of finalize() runs?

class Box{
private int iVolume;
Box(int iVolume){
public void finalize(){
System.out.println("finalizing a Box");

public class EdGrundy{
boolean stop = false;
public static void main(String argv[]){
new EdGrundy();
new Box(99);
Arnab Sinha
Ranch Hand

Joined: Jul 23, 2006
Posts: 72
Finalize method is inherited from Object class. So when you are using it in your class, the rules of overriding are applied. One of the rules is that the overriden method may have a less restritive access modifier than the parent class and must not have a more restrictive access modifier. This is the reason why your code compiles and runs.

SCJP 1.4: 91%<br />SCWCD 1.4: 85%
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Just the same as

compiles and output is Beta

all events occur in real time
parshuram bingi

Joined: Aug 01, 2006
Posts: 10
Hi all,

I changed the original program to
new Box(99);

nothing is printed. but when the while loop is running the "finalizing a Box" string is printed continuously why?

Hard Work, Honesty(2H) pays...
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi cowboys!

If you //delete the loop only one object is made. You cannot say when the garbage collector will run. Probably he isn't caring about just one object and leaves it alone.
With the endless loop the garbage collector is pretty busy though.

What if you experiment a bit using a for loop running 100.000 times, or less, or more?
There is a chance for the GC to run (and so the finalize method) with having only one Box if you invoke System.gc(); after.
But only a chance, there's no garanty that it will run. But there's a garanty that GC will invoke finalize on each object only once.

I agree. Here's the link:
subject: GC question
It's not a secret anymore!