Is an object ready for garbage collection? I understood more or less the garbage collector but I want to test in practice.Topic Java

Viewed 46

Below is example with cats method.Is this looks right?

 public class Objects{
    //when an object has been dereferenced 
    public void cats(){
      System.out.println("wet food!");
     
     }
    public static void main(String[]args){
     Objects myCatwants = new Objects();
     myCatwants.cats();
     System.out.println("end of method");//out cats method is ready for garbage collection

       }
    }

Thank you very much in advance!

1 Answers

Is this looks right?

It has a compilation error, but I understand what you mean by the code.

     Objects.myCatwants = new Objects();

should be

     Objects myCatwants = new Objects();

Yes. When the main method returns, the Objects object that it created will no longer be reachable, and will be eligible for garbage collection.

(In fact, depending on how smart the Java implementation is, it is potentially eligible for garbage collection as soon as the call to cats() has returned. Or it could even optimize away the creation of an Objects instance in the heap!)

However, in practice the program will almost certainly terminate before the garbage collector runs. The garbage collector is run when the JVM deems it necessary. In this example, it would most likely be impossible to arrange a situation where it was going to be necessary.

Related