I was reading interview questions randomly on different sites and came across this question. They have mentioned that till 1.7 substring
holds reference to the original string. So if you even choose small part of bigger string, it can't be GC. This problem is resolved in 1.7.
I have checked src code for both 1.6 and 1.8 and doesn't find any difference in the implementation. Any idea?
You are right
Pre‑Java7 implementations kept a reference to the whole backing array. If that is much larger than the substring it can cause a memory leak. It was the only instance (I think) where it was worth using the String copy constructor.
String s = myText.substring(123, 456); // Risk of keeping whole backing array
String s = new String(myText.substring(123, 456)); // No risk of memory leak
As you said, since Java7 that trick has been unnecessary.