I wrote this piece of code and ran it:
package com.nik.practice;
import java.io.IOException;
public final class StrTest {
static
String st;
public static void main(String[] args) {
StrTest t = new StrTest();
st = "first";
st = null;//the object is made eligible for garbage collection here
try{
t.finalize(); }catch(Throwable e){
}
System.gc();
System.out.println("st is "+st);
}
protected void finalize(){
st = "first";//here the object is again made alive
}
}
In above I call finalize explicitly and in this case the object is properly referenced again.So "first" is printed as expected.
Now I just commented the call to finalize and ran the code again:
i.e I did
try{
//t.finalize(); }catch(Throwable e){
}
This time though null is printed.I would like to know why because I have overridden the finalize method.And as per the JVM spec when System.gc is called an Object's finalize() is called.Why then doesn't the object get referenced again?I am I missing some important point?