How does substring() method work in JDK 1.6
String in Java is a sequence of characters (maintained in char array value). The string is more like a utility class which works on that character sequence.
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. Yes, you heard it correct. Memory leak.
If you have a VERY long string and need a small part each time by using substring() method, this will return the offset and count which refers to the original string array which will not permit to garbage collection of original string array. Example, you require the first 2 characters from the 10 MB size string, the Java 1.6 substring method will not garbage collect the Original string that is of 10 MB and not in use.
This will cause a performance problem, since we need only a small part and keeping the whole char value array (No garbage collection).
Resolve the memory leak in JDK 1.6
In above code, the string.substring(3, 10) will return the substring which points to an 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, a new string will form in the constant pool with new char value array and we can overcome the problem of garbage collection of an old string array.