4

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.

user1216750
  • 483
  • 3
  • 10
  • 17
  • 1
    It would live until at least the `start()` method finished executing, there is _no_ guarantee about object lifetimes in Java since memory is managed by the garbage collecter and not the programmer. – Hunter McMillen Jun 22 '12 at 13:52

3 Answers3

6

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.

Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
2

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());
}
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
2

The exact lifetime is determined by the garbage collector: once there are no more references to the object it can be reclaimed by the GC. In your case it will live until at least the end of ClassB.start() as there are no more references to if once that method finished

Attila
  • 28,265
  • 3
  • 46
  • 55