Systemsfailed
Systemsfailed

Reputation: 3

Do variables declared in constructors persist in the created object

If I want to declare a temp int within the constructor of an object, will that variable stay in memory after the construction is finished. Or will garbage collection remove it after its finished?

Upvotes: 0

Views: 115

Answers (2)

Steve C
Steve C

Reputation: 19445

int, long, boolean and other primitive variables are never garbage collected as they occupy space in the thread stack.

Their memory utilisation is recovered the moment that the method call (including constructors) returns to the caller.

Upvotes: 0

Emile P.
Emile P.

Reputation: 3962

Once the variable goes out of scope and you're not keeping a reference to it and garbage collection runs, it will be removed from memory. This is not guaranteed to happen right after the constructor finishes executing, though - it can take some time, depending on the situation.

Upvotes: 2

Related Questions