简体   繁体   中英

Object Destruction in Java

From the below example, In Case 1 the object is created in Class level and in Case 2 its created in Method level.

My understanding that in Case 2 once the method completes its execution the object is removed from heap memory . Is my understanding correct ?

Now My question is,in both the cases when will the object be removed from the Heap memory and which is efficient way of using in different context ?

public class A()
    {
        ClassB obj = new ClassB(); // Case 1
        private void method()
        {
            ClassB obj = new ClassB(); // Case 2
        }

    }

Might depend on your Java VM implementation, but generally GC is run only after the heap is filled / saturated. So no, most probably it won't be removed immediately.

In Your program. you have written only one line in which only declaration and initialization done. and one more thing i want to ask that is it class , Method or constructor .

private example(){ //what is example ?? Is it class or method or constructor ?
      ClassA obj = new ClassA();
    }

but i want to tell you ClassA obj will be eligible for gc after the } (Closing Paranthesis) execution done. but it is totally depends upon the jvm that when gc will be executed then collect and destroy the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM