Radiance
Radiance

Reputation: 54

Why finalize is not giving null pointer exception in the below code?

Why the below code is not giving null pointer exception in the finalize method when the objects are made null??

class Person{  
public int a;
public void finalize(){
    //System.out.println("finalize called"+this.hashCode());
    System.out.println("finalize called"+this.a);
}  
public static void main(String[] args){  
    Person f1=new Person();  
    f1.a=10;
    Person f2=new Person();  
    f1=null;  
    f2=null;  
    System.gc();  
}}

O/P : finalize called0 finalize called10

Upvotes: 0

Views: 227

Answers (3)

Onic Team
Onic Team

Reputation: 1658

class Person{  
public int a;
public void finalize(){
    //System.out.println("finalize called"+this.hashCode());
    System.out.println("finalize called"+this.a);
}  
public static void main(String[] args){  
    Person f1=new Person();  
    f1.a=10;
    Person f2=new Person();  
    f1=null;  
    f2=null;  
    System.out.println("f1 =" + f1 + " f2 = " + f2);
    System.gc(); 
    System.out.println("Below gc");

    System.out.println();
    System.out.println(f1.a);// **here O/P - NPE**
}}

OUTPUT ->

f1 =null f2 = null

Below gc

finalize called0 finalize called10

Exception in thread "main" java.lang.NullPointerException at basic.Person.main(Person.java:19)

Upvotes: 0

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36391

Objects are never made null, this is non-sense. References can be made null, and objects can be destroyed (as a consequence).

f1 and f2 are not objects, they are reference to objects. When you write f1=null that just means that this reference does not point to any object anymore and that the object that was previously pointed to has one reference less. The garbage collection (roughly) tracks all manipulations of references you make, and when objects are not referred anymore they are first put in some trash and then recycled or destroyed if needed, but object are existing even in that phase. When recycled/destroyed the machine will call finalize on it just before the recycling/destroying, then object exists at the time finalize is called (if not, how could finalize be called on the object?).

Upvotes: 1

Kayaman
Kayaman

Reputation: 73528

Objects can't be made null, only references.

Just because you set f1 and f2 to null, doesn't mean that finalize() would throw a NPE. It's accessing the this reference which can never be null.

f1 --> Object <-- (implicit this accessible from inside the instance)
f2 --> Object <-- (--""--)

f1 = null; f2 = null;

       Object <-- (implicit this) previously f1 referred to this Object
       Object <-- (implicit this) previously f2 referred to this Object

Upvotes: 1

Related Questions