0_1_2_3_4_5 |h|e|l|l|o| 0_1_2_3_4_5
"hello".substring( 1 ,3 ) == "el";substring is clever. It does not make a deep copy of the substring the way most languages do. It just creates a pointer into the original immutable String, i.e. points to the value char[] of the base string, and tracks the starting offset where the substring starts and count of how long the substring is. This could be confusing if you were low-level debugging since you would see the whole String, not just the substring. There were reports of a bug in Microsoft’s implementation of substring. The downside of this cleverness is a tiny substring of a giant base String could suppress garbage collection of that big String in memory even if the whole String were no longer needed. (actually its value char[] array is held in RAM; the String object itself could be collected.)
It is probably still a good idea to use indexOf( lookFor, offset ) rather than creating a substring first and using indexOf( lookFor ) on that.
If you know a tiny substring is holding a giant string in RAM, that would otherwise be garbage collected, you can break the bond by using littleString = new String( littleString ) which will create a new smaller backing char[] with no ties to the original String.
If you are a curious sort, and study the code for String. substring in src.zip, this sharing logic might not be apparent. The key is a non-public String constructor that takes parameters in the reverse of the usual order String (int offset, int count, char value[]).
| You can get the freshest copy of this page from: | or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror) | |
| http://mindprod.com/jgloss/substring.html | J:\mindprod\jgloss\substring.html | |
![]() | ||
| Canadian Mind Products | ||
| mindprod.com IP:[65.110.21.43] | ||
| view Blog | Your face IP:[38.107.191.113] | |
| Feedback | You are visitor number 152,226. | |