About the String#substring() method

Posted by alain.janinm on Stack Overflow See other posts from Stack Overflow or by alain.janinm
Published on 2012-06-20T09:12:50Z Indexed on 2012/06/20 9:16 UTC
Read the original article Hit count: 224

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about string