-4

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
        }

    }
Nenapu
  • 1
  • 3
  • 3
    it wil be removed when the garbage collector decides to do so. How garbage collection works exactly in java is a little bit to complicated to explain in a few sentences and you can either read up about it on external sources or not worry about it as you really don't need to. – OH GOD SPIDERS Sep 28 '17 at 10:20
  • duplicate to https://stackoverflow.com/questions/171952/is-there-a-destructor-for-java – Shivam Sep 28 '17 at 10:24
  • Right after the `;` the object is eligible for garbage collection. The garbage collection can decide how to best remove all, and do it in sweeps. Compared to C with explicit allocation, freeing, this can behave better. – Joop Eggen Sep 28 '17 at 10:25

2 Answers2

0

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.

px1mp
  • 5,212
  • 1
  • 18
  • 10
  • 1
    It *does* depend on the JVM .... and the GC that you select. A low-pause collector will often be collecting in the background ... before the heap is full. – Stephen C Sep 28 '17 at 10:44
0

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.

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52