Http://clarkht.iteye.com/blog/482644
String oldstr = "Hello, Clark ";
String newstr = oldstr. substring (0, 4 );
In fact, for oldstr, It is a char [] array [h, E, l, l, 0, C, L, A, R, K], for the substring operation, newstr does not copy the char [] array of oldstr by itself. Hello creates a new char [] array, but Java implements string reusing optimization behind it, instead of creating a new char array, it reuses the original char array. So there won't be many fragments of the original char [] array. Reference columns on http://www.javablogging.com/string-and-memory-leaks:
Java code
Public static void sendemail (string emailurl ){
String email = emailurl. substring (7); // 'mailto: 'prefix has 7 letters
String username = Email. substring (0, email. indexof ("@"));
String domainname = Email. substring (email. indexof ("@"));
}
Public static void main (string [] ARGs ){
Sendemail ("mailto: user_name@domain_name.com ");
}
However, this is generally good, but it also has a price. According to explain collected, because newstr still has reference to the char [] array of oldstr. This can easily cause an outof Memory exception. The solution is to enable newstr to own its char [] array, that is, force itself to create its char [] array during substring, in this way, there will be no garbage collected problems (reachable but unused !) What to do:
Java code
String sub = new string (oldstring. substring (0, 4 ));
---------------------------------------------------------------
To avoid Memory copying and speed up, Sun JDK directly reuses the char [] of the original string object, and uses the offset and length to identify different string content. That is to say, the small String object produced by substring still points to the char [] of the large string object. The same is true for split. This explains why the char [] of the string object in hashmap is so big.
-------------------------------------------------------
Refer:
Http://jarfield.iteye.com/blog/583946