Here, in the first case, when you create a string object using new String("I'm here") , so the object is always created on heap.So then, if you call System.gc(); Then this object can be directly accessible for garbage collection.
While in the second case, you pass the string as an object reference. A new String object will not be created here, since the string is directly initialized with a reference to the object. So it will not be available for garbage collection. Since this string will remain in the string-pool .
source share