String a="ABC";
a="BCD";
System.out.println(a); //BCD
What happens to "ABC"? Can someone explain me what will happen?
String a="ABC";
a="BCD";
System.out.println(a); //BCD
What happens to "ABC"? Can someone explain me what will happen?
When you perform String a="ABC"
, your string literal get's automatically added to String pool. It's kept in string pool so that JVM can reuse it if it can be.
After this, the rules for garbage collecting of string is same as that of any other object. Before we assign any other object to a
variable, if "ABC"
was referenced by any other variable, then it will stay there in the pool.
Otherwise, if it's not referenced anymore, then it will get garbage collected the very next time GC runs.