About the String#substring() method
- by alain.janinm
If we take a look at the String#substring method implementation :
new String(offset + beginIndex, endIndex - beginIndex, value);
We see that a new String is created with the same original content (parameter char [] value).
So the workaround is to use new String(toto.substring(...)) to drop the reference to the original char[] value and make it eligible for GC (if no more references exist).
I would like to know if there is a special reason that explain this implementation. Why the method doesn't create herself the new shorter String and why she keeps the full original value instead?
The other related question is : should we always use new String(...) when dealing with substring?