Careful about String class instantiation in exam and garbage collection, the String s = "hello"; s = null; is not garbage collected but String s = new String ("hello"); s = null; is garbage collected. Can somebody explain this? It is kinda conflicting...
>>String s = "hello"; >>s = null; Java optimizes handling of string literals by implementing them as anonymous objects that can be shared. Strings that have the same literal contents share the same anonymous object. Consider this code:
Both of the print statement will print true. This means that this form of initialization does not create new objects. It only creates a reference that points to an anonymous object that cannot be garbage collected.
>>String s = new String ("hello"); >>s = null; This form of initialization, however, creates a new String object. Again, consider this code:
The first print statement will print false. s2 now points to a newly created object that can be garbage collected.