How does substring() method works in JDK 1.6
String in java is a sequence of characters (maintained as char array value[]).
String is more like a utility class which works on that character sequence.
private final char value[];
/** The offset is the first index of the storage that is used. */
private final intoffset;
/** The count is the number of characters in the String. */
private final intcount;
These two private variables (offset and count)used to manage the char array.
When we create a substring of String using substring() method, this method assigns the new values of offset and count variables every time.
Problem with above approach till JDK 1.6 (Memory leak)
If you have a VERY long string, but we only need a small part each time by using substring(). substring() method will return the offset and countwhich refers the original string array which will not permit to garbage collection of original string array.
This will cause a performance problem, since we need only a small part and keeping the whole char value[] array (No garbage collection).
public String substring(int beginIndex, intendIndex) {
//check boundary
return ((beginIndex == 0) && (endIndex == count))?this :
newString(offset + beginIndex, endIndex - beginIndex, value);
}
String(intoffset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
Resolve the memory leak in JDK 1.6
subString = string.substring(3, 10) + "";
In above code, the string.substring(3, 10) will return the substring which point to original string array and the substring will not allow the garbage collection for old string (char value[]).
But when we add the empty string to offset, new string will form in constant pool with new char value[] array and we can overcome the problem of garbage collection of old string array.