Search code examples
javalifetimeobject-lifetime

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?


Solution

  • 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/