Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Life of a Java Object

What is the life of a Java Object that is passed a method argument?

For example I have an object Test

class Test{

    public string testType(){
       .....
    }
}

and I have two classes A and B

class classA{

   classB b = new classB();

   void nextQuestion{
      b.start(new Test());
   }
}




class classB{
   void start(Test test){
      doSomething(test.testType());
   }
}

so now what is the life of the Test object? Is it only till the end of the start method or will it be alive till the end of classB or while it alive till the end of classA or is something else.

like image 313
user1216750 Avatar asked Oct 19 '25 20:10

user1216750


2 Answers

It will stay atleast till the end of start() method, because it has been declared there, and that is its scope. Beyond that, its existence is in the hands of the garbage collector.


EDIT:

By end of start() I mean, till that method ends it's execution. And even if you make the changes that you have shown, that Object is still needed by the start() method, so it will still only exist atleast till the execution of start() method is over, beyond that it depends on the garbage collector.

like image 54
Kazekage Gaara Avatar answered Oct 21 '25 09:10

Kazekage Gaara


Its life begins when new Test() is called, and it may be released by the garbage collector any time after the start method finishes, because it is provable at compile time that it will never be used after that point.

If the start method were to (for example) set a static field to refer to the object, the garbage collector could not collect it until that reference was released:

private static Test lastTested;
...

void start(Test test){
   lastTested = test;
   doSomething(test.testType());
}
like image 39
StriplingWarrior Avatar answered Oct 21 '25 11:10

StriplingWarrior