April 24, 2016

#Java: Part 14-How does substring() inside String works?

Substring creates a new object out of source string by taking a portion of the original string. It is defined in defined in java.lang.String class.

substring() has two variants:-
  • substring(int beginIndex): returns the substring starting from the specified index. The beginIndex is inclusive. This method throws IndexOutOfBoundsException if the beginIndex is less than zero or greater than the length of String.
  • substring(int beginIndex, int endIndex): returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1. Thus the length of the substring is endIndex-beginIndex (beginIndex is inclusive and endIndex is exclusive while getting the substring).
If beginIndex is equal to length in substring(int beginIndex) it won't throw IndexOutOfBoundException instead it will return empty String. Same is the case when beginIndex and endIndex is equal.

ALSO READ: Why String is immutable or Final in Java?

How substring() works?
If you look substring() method of String class, you will find that it internally calls String (int offset, int count, char value []) constructor to create new String object. Here value[] is the same character array used to represent original string.

subString method of Java 6

String constructor in Java 6

If the original string is very long( say of size 1GB), no matter how small a substring is, it will hold 1GB array. This will also stop original string to be garbage collected, in case if doesn't have any live reference. This can cause memory leak, because memory is retained even if it's not required.

Until Java 1.7, substring holds the reference of the original character array, this issue was fixed in Java 1.7, where the original character array is not referenced anymore, but that change also made the creation of substring a bit costly in terms of time. Earlier it was on the range of O(1), which could be O(n) in the worst case of Java 7 onwards.


subString method of Java 8
String constructor in Java 8

ALSO CHECKCore Java Interview Questions And Answers

-K Himaanshu Shuklaa..

No comments:

Post a Comment

RSSChomp Blog Directory