Search code examples
garbage-collectionmember-variables

The Member Variable in java is GC root it?


I see a lot of explain about what is gc root.And i know local variable and params is gc root.But member variable is not gc root? If i type code in class body

    Person p = new Person("Lily");
    public void sayHello(){
        System.out.println(p.name);
    }

So,p is not local var but member var.If p is not GC root,it may be collection.And will have null point exception in sayHello method.


Solution

  • Person p will be root object. It would be hierarchical like:

    person
      |
    name
    

    Also it wont end up in null pointer exception, as you initialized p and then you are trying to access name on it.

    Nullpointer will only hit, if you defined p as null like Person p = null

    And now you try to access name on it System.out.println(p.name);