Java substring() method memory leak issue and fix
Last Updated :
12 Sep, 2022
String is a special class in Java. substring() is one of the widely used methods of String class. It is used to extract part of a string and has two overloaded variants:
1. substring(int beginIndex):
This method is used to extract a portion of the string starting from beginIndex.
Example:
Java
class GFG {
public static void main(String args[]) {
String s = "geeksforgeeks" ;
String subString = s.substring( 4 );
System.out.print(subString);
}
}
|
The beginIndex parameter must be within the range of source string, otherwise you would see the following exception:
java.lang.StringIndexOutOfBoundsException: String index out of range:
2. substring(int beginIndex, int endIndex):
This variant accepts two parameters beginIndex and endIndex. It breaks String starting from beginIndex till endIndex – 1.
Example:
Java
class GFG {
public static void main(String args[]) {
String s = "geeksforgeeks" ;
String subString = s.substring( 5 , 13 );
System.out.print(subString);
}
}
|
How substring() works internally
We all know that String in Java is sequence of characters. String is internally represented by array of characters, when new String object is created, it has following fields.
- char value[] – Array of characters
- int count – Total characters in the String
- int offset – Starting index offset in character array
String s = “geeksforgeeks”;
value[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’}
count = 13
offset = 0
When we take substring from original string, new String object will be created in constant pool or in heap. The value[] char array will be shared among two String objects, but count and offset attributes of String object will vary according to substring length and starting index.
String s = “geeksforgeeks”;
String substr = s.substring(5, 8)
For substr:
value[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’}
count = 3
offset = 5

Problem caused by substring() in JDK 6
This method works well with small Strings. But when it comes with taking substring() from a String with more characters, it leads to serious memory issues if you are using JDK 6 or below.
Example:
String bigString = new String(new byte[100000])
The above String already occupies a lot of memory in heap. Now consider the scenario where we need first 2 characters from bigString,.
String substr = bigString.substring(0, 2)
Now we don’t need the original String.
bigString = null
We might think that bigString object will be Garbage collected as we made it null but our assumption is wrong. When we call substring(), a new String object is created in memory. But still it refers the char[] array value from original String. This prevents bigString from Garbage collection process and we are unnecessarily storing 100000 bytes in memory (just for 2 characters). The bug details can be found here.
Handling substring() in JDK 6
This issue should be handled by developers. One option is creating new String object from substring returned String.
String substr = new String(bigString.substring(0, 2))
Now, new String object is created in java heap, having its own char[] array, eventually original bigString will eligible for garbage collection process.
Other option is, call intern() method on substring, which will then fetch an existing string from pool or add it if necessary.
String substr = bigString.substring(0, 2).intern()
Fix for substring() in JDK 7
Sun Microsystems has changed the implementation of substring() from JdK 7. When we invoke substring() in JDK 7, instead of referring char[] array from original String, jvm creates new String objects with its own char[] array.
Java
public String( char value[], int offset, int count) {
this .value = Arrays.copyOfRange(value, offset, offset + count);
}
public String substring( int beginIndex, int endIndex) {
int subLen = endIndex - beginIndex;
return new String(value, beginIndex, subLen);
}
|

It is worth noting that, new String object from memory is referred when substring() method is invoked in JDK 7, thus making original string eligible for garbage collection.
Similar Reads
Remove first and last character of a string in Java
Given a string str, the task is to write the Java Program to remove the first and the last character of the string and print the modified string. Examples: Input: str = "GeeksForGeeks"Output: "eeksForGeek"Explanation: The first and last characters of the given string are 'G' and 's' respectively. Af
5 min read
Reverse a String in Java
In Java, reversing a string means reordering the string characters from the last to the first position. Reversing a string is a common task in many Java applications and can be achieved using different approaches. In this article, we will discuss multiple approaches to reverse a string in Java with
7 min read
Split a String into a Number of Substrings in Java
Given a String, the task it to split the String into a number of substrings. A String in java can be of 0 or more characters. Examples : (a) "" is a String in java with 0 character (b) "d" is a String in java with 1 character (c) "This is a sentence." is a string with 19 characters. Substring: A Str
5 min read
How to Optimize Memory Usage and Performance for large HashSet Datasets in Java?
HashSet is mainly used for the data structures in Java offers fast access and prevents duplicate elements. So, the size of the dataset will be improved and it can raise memory consumption and performance issues. Now we are discussing exploring the various strategies to optimize memory usage and enha
3 min read
Trim (Remove leading and trailing spaces) a string in Java
In Java, the trim() method is used to remove leading and trailing spaces from a string. This method does not remove spaces between words but it eliminates unnecessary spaces at the beginning and end of the string. The trim() method is defined under the String class in the java.lang package. It check
1 min read
Java String startsWith() and endsWith() Methods With Examples
In Java, the startsWith() and endsWith() methods of the String class are used to check whether a string begins or ends with a specific prefix or suffix, respectively. Example: This example demonstrates the usage of the startsWith() and endsWith() methods in Java. [GFGTABS] Java // Java Program to de
2 min read
Java Program to Remove a Given Word From a String
Given a string and a word that task to remove the word from the string if it exists otherwise return -1 as an output. For more clarity go through the illustration given below as follows. Illustration: Input : This is the Geeks For Geeks word="the" Output : This is Geeks For Geeks Input : Hello world
3 min read
Java Program To Remove Duplicates From A Given String
Write a java program for a given string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string. Note: The order of remaining characters in the output should be the same as in the original string.Example: Input: Str = geeksfor
3 min read
Files Class writeString() Method in Java with Examples
The writeString() method of File Class in Java is used to write contents to the specified file. Syntax: Files.writeString(path, string, options) Parameters: path - File path with data type as Pathstring - a specified string which will enter in the file with return type String.options - Different opt
2 min read
Files Class readString() Method in Java with Examples
The readString() method of File Class in Java is used to read contents to the specified file. Syntax: Files.readString(filePath) Parameters: path - File path with data type as Path Return Value: This method returns the content of the file in String format. Below are two overloaded forms of the readS
1 min read