-4
String a="ABC";
a="BCD";
System.out.println(a); //BCD

What happens to "ABC"? Can someone explain me what will happen?

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103

2 Answers2

2

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.

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0

'ABC' gets garbage collected since it has lost reference

henrybbosa
  • 1,139
  • 13
  • 28