Menu
Topics Index
...
`

Garbage Collection - Java Example Program


Garbage Collection
class garbagedemo
{
    public static void main(String arg[])
    {
        Garbage obj=new Garbage();
                Garbage obj1=new Garbage();  // LINE B
                obj.setdata(10,20);
                obj.printdata();
                obj1=null;
                System.gc();  // Method to call garbage collector
                obj.printdata();  // LINE A
    
    }
}

class Garbage extends Object
{
    int x,y;
    void setdata(int a , int b )
    {
        x = a ;
        y = b ;
    }
    void printdata()
    {
        System.out.println("x="+x+" y=" + y);
    }
    protected void finalize()
    {
        System.out.println("Finalizer");
    }
}
OUTPUT

x=10 y=20
Finalizer
x=10 y=20

DESCRIPTION

  • This program says that how to call the call garbage collector.
  • finalize() keyword defines in java.lang.Object class, which means it available to all the classes for sake of overriding.

THINGS TO TRY
  • If you place
    obj1.setdata(2,3);
    in LINE A. It shows an error called
    x=10 y=20 Exception in thread "main" Finalizer java.lang.NullPointerException at garbagedemo.main(garbagedemo.java:13)
  • If you not create object1 in LINE B. It doesnot finalize through finalizer check out once. you take off the line and execute once .

© meritcampus 2019

All Rights Reserved.

Open In App