SubString in Java is a useful method from
java.lang.String class, which is used to create smaller
String from bigger ones. The way Substring works prior to Java 1.7, can create subtle
memory leak, because both
String and their substring shares same character array. Which means, if you have a big
String of
200MB and created substring of
2MB from that, that could prevent
200MB String from being garbage collected. I agree this doesn't look normal and indeed was a bug, but it was like that till Java 1.6 and it's various update. One reason, which I could think, why Java designer initially thought like that, may be to save memory by sharing char array and to make, creating
substring faster by just copying pointers, instead of data. Nevertheless, this was reported as bug and
Oracle has fixed it, so no more
substring memory leak issue in Java 7. This issue doesn't undermine important of substring method, which is one of the most important one from
java.lang.String class. One thing, which is also worth remembering is that, whenever you call substring method, it return a separate String object, because
String is immutable in Java. In next section we will see syntax of substring method and How to use it for practical purpose.