Anand
Anand

Reputation: 21310

Garbage collection of String in java

Suppose a string in Java is declared as String s = "hi"

I just want to know if the String object created above will ever be garbage collected?

if i write s = null, at this point will the String object be garbage collected?

Upvotes: 2

Views: 205

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533442

The JVM loads String literals into a String constant pool. This is not done by the javac or JIT compiler. A String loaded into the comnstant pool this way can be cleaned out like any other object, when there is no more references to the object. This would require that the class be unloaded but this can happen if your application works this way.

Upvotes: 1

Jimmy
Jimmy

Reputation: 2619

Take it this way, the compiler will move it to the literal pool. Now all the instance of "hi" will be replaced by this value in the pool , which is actually a way compiler optimizes memory usage. No, these values are never garbage collected . However String object created at runtime would be garbage collected.

Upvotes: 2

Related Questions