darkalbo
darkalbo

Reputation: 343

Java inline object passed as parameter lifetime

What's the lifetime of an object created inline and passed to a method? For example:

myMethod(new String("Hello World"));

The String "Hello World" is created and destroyed just after the myMethod execution or it still remains in memory until Garbage Collector removes it?

Upvotes: 1

Views: 170

Answers (2)

Brennan Bennett
Brennan Bennett

Reputation: 95

Im pretty sure it will only exist in the method unless you assign it to a global variable.

Upvotes: 0

nirali.gandhi
nirali.gandhi

Reputation: 221

JAVA treats String Literal differently. Here String object with value "Hello World" would be created in String Constant Pool.

And the life time of this literal in Constant Pool would be decided by JVM which means JVM will decide when to collect it for garbage (like there is no more memory in Constant pool and now this object is not referenced by any reference).

But it will not get destroyed immediately after the method execution.

you can find more detail on String constant pool here: http://www.thejavageek.com/2013/06/19/the-string-constant-pool/

Upvotes: 7

Related Questions